巅峰对决!Spring Boot VS .NET 6
wptr33 2025-04-29 05:36 33 浏览
Spring Boot 和 ASP.NET Core 都是企业中流行的 Web 框架, 对于喜欢 C# 的人会使用 ASP.NET Core, 而对于 Java 或 Kotlin 等基于 JVM 的语言,Spring Boot 是最受欢迎的。
这本文中,会对比这两个框架在以下方面有何不同:
- 控制器
- 模型绑定和验证
- 异常处理
- 数据访问
- 依赖注入
- 认证与授权
- 性能
基础项目
这是一个有关订单的基础项目, 非常简单的后端 api, 客户可以创建一个订单来购买一个或多个产品, 我使用了 MySQL 作为数据库,下面是实体关系图。
这里使用的框架版本分别是, Spring Boot (v2.5.5) 和 .NET 6, 让我们开始对比吧!
1.控制器
控制器是负责处理传入请求的层, 为了在 Spring Boot 中定义一个控制器,我创建了一个类 ProductOrderController, 然后使用了 @RestController 和 @RequestMapping 注解, 然后在控制器的每个方法上, 可以使用下面的注解来定义支持的 HTTP 方法和路径(可选)。
- @GetMapping
- @PostMapping
- @PutMapping
- @DeleteMapping
- @PatchMapping
如果要绑定到路径变量, 我们可以将参数添加到用 @PathVariable 注释的控制器方法中,并指定与参数同名的路由路径模板,下面的 getOrderById() 方法,我们将id绑定为路径变量。
@RestController
@RequestMapping("/v1/orders")
class ProductOrderController(
private val productOrderService: IProductOrderService
) {
@GetMapping
fun getOrders(query: ProductOrderQuery): List<ProductOrderDto> = when {
query.productId?.isNotEmpty() == true -> productOrderService.getByProductId(query.productId!!)
query.customerId?.isNotEmpty() == true -> productOrderService.getByCustomerId(query.customerId!!)
else -> productOrderService.getAllOrders()
}
@GetMapping("{id}")
fun getOrderById(@PathVariable id: String): ProductOrderDto = productOrderService.getById(id)
}
在 .NET Core 中, 控制器和上面是相似的, 首先创建一个 ProductOrderController 类, 并继承 ControllerBase ,标记 [ApiController] 特性, 然后通过 [Route] 特性指定基本路径, 然后在控制器的每个方法上, 可以使用下面的特性来定义支持的 HTTP 方法和路径(可选)。
[ApiController]
[Route("v1/orders")]
public class ProductOrderController : ControllerBase
{
private readonly IProductOrderService _productOrderService;
public ProductOrderController(IProductOrderService productOrderService)
{
_productOrderService = productOrderService;
}
[HttpGet]
public async Task<List<ProductOrderDto>> GetOrders([FromQuery] ProductOrderQuery query)
{
List<ProductOrderDto> orders;
if (!string.IsNullOrEmpty(query.ProductId))
{
orders = await _productOrderService.GetAllByProductId(query.ProductId);
}
else if (!string.IsNullOrEmpty(query.CustomerId))
{
orders = await _productOrderService.GetAllByCustomerId(query.CustomerId);
}
else
{
orders = await _productOrderService.GetAll();
}
return orders;
}
[HttpGet("{id}")]
public async Task<ProductOrderDto> GetOrderById(string id) => await _productOrderService.GetById(id);
}
模型绑定和验证
在 Spring Boot 中, 我们只需要给控制器的方法的参数加上下面的注解
- @RequestParam → 从查询字符串绑定
- @RequestBody → 从请求体绑定
- @RequestHeader → 从请求头绑定
对比表单的请求,不需要给参数加注解就可以绑定。
@RestController
@RequestMapping("/v1/customer")
class CustomerController(
private val customerService: CustomerService
) {
@PostMapping("/register")
fun register(@Valid @RequestBody form: RegisterForm) = customerService.register(form)
@PostMapping("/login")
fun login(@Valid @RequestBody form: LoginForm) = customerService.login(form)
}
@RestController
@RequestMapping("/v1/orders")
class ProductOrderController(
private val productOrderService: IProductOrderService
) {
@GetMapping
fun getOrders(query: ProductOrderQuery): List<ProductOrderDto> {
...
}
}
如果要对参数进行验证, 需要添加
spring-boot-starter-validation 依赖项, 然后给 DTO 的属性加上 @NotEmpty 、 @Length 等注解, 最后给DTO加上 @Valid 即可。
.NET Core 和上面类似, 同样你可以使用下面的特性标记控制器的方法
- [FromQuery] → 从查询字符串绑定
- [FromRoute] → 从路由数据绑定
- [FromForm] → 从表单数据绑定
- [FromBody] → 从请求体绑定
- [FromHeader] → 从请求头绑定
[Route("v1/customer")]
[ApiController]
public class CustomerController : ControllerBase
{
[HttpPost("register")]
public async Task<AuthResultDto> Register([FromBody] RegisterForm form) => await _customerService.Register(form);
[HttpPost("login")]
public async Task<AuthResultDto> Login([FromBody] LoginForm form) => await _customerService.Login(form);
}
[Route("v1/orders")]
[ApiController]
public class ProductOrderController : ControllerBase
{
[HttpGet]
public async Task<List<ProductOrderDto>> GetOrders([FromQuery] ProductOrderQuery query)
{
.....
}
}
模型验证也是类似的, 给 DTO 的属性上加上 [Required]、[MinLength]、[MaxLength] 等特性就可以了。
public class RegisterForm
{
[Required(ErrorMessage = "Please enter user id")]
public string UserId { get; set; }
[Required(ErrorMessage = "Please enter name")]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter password")]
[MinLength(6, ErrorMessage = "Password must have minimum of 6 characters")]
public string Password { get; set; }
}
异常处理
Spring Boot 的异常处理,主要用 @RestControllerAdvice 和 ExceptionHandler
注解,如下
abstract class AppException(message: String) : RuntimeException(message) {
abstract fun getResponse(): ResponseEntity<BaseResponseDto>
}
@RestControllerAdvice
class ControllerExceptionHandler : ResponseEntityExceptionHandler() {
@ExceptionHandler(AppException::class)
fun handleAppException(ex: AppException, handlerMethod: HandlerMethod): ResponseEntity<BaseResponseDto> {
return ex.getResponse()
}
}
在 ASP.NET Core 中,异常处理程序被注册为过滤器/中间件,我们可以创建一个异常处理类,并继承 IExceptionFilter 接口。
public class ControllerExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
if (context.Exception is AppException exception)
{
context.Result = exception.GetResponse();
}
}
}
然后注册这个异常过滤器
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers(options =>
{
options.Filters.Add<ControllerExceptionFilter>();
});
数据访问
在 Spring Boot 中, 你可以使用 Hibernate ORM, 创建一个Repository 接口, 并继承 JpaRepository , 这样就有了开箱即用的基本查询方法,比如 findAll() 和 findById()。
您还可以在定义自定义查询方法。只要遵循严格的方法命名约定,Spring 就会构建这个存储库的实现,包括运行时的所有查询,魔法?是的!
interface IProductOrderRepository : JpaRepository<ProductOrder, String> {
@EntityGraph(type = EntityGraph.EntityGraphType.FETCH, value = "product-order-graph")
override fun findById(id: String): Optional<ProductOrder>
@EntityGraph(type = EntityGraph.EntityGraphType.FETCH, value = "product-order-graph")
fun findAllByCustomer(customer: Customer): List<ProductOrder>
@EntityGraph(type = EntityGraph.EntityGraphType.FETCH, value = "product-order-graph")
@Query("SELECT ord FROM ProductOrder ord JOIN OrderItem item ON item.productOrder = ord WHERE item.productId = :productId")
fun findAllByProductId(productId: String): List<ProductOrder>
}
而在 .NET Core 中,我们可以使用官方的 Entity Framework ORM, 首先,我们需要创建一个 DB Context 类, 这是 ORM 框架用来连接数据库和运行查询的桥梁。
public class AppDbContext : DbContext
{
public DbSet<Customer> Customer { get; set; }
public DbSet<Product> Product { get; set; }
public DbSet<ProductOrder> ProductOrder { get; set; }
public DbSet<OrderItem> OrderItem { get; set; }
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
Customer = Set<Customer>();
Product = Set<Product>();
ProductOrder = Set<ProductOrder>();
OrderItem = Set<OrderItem>();
}
}
接下来,还需要注册上面的 DB Context,并配置数据库连接字符串
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddDbContext<AppDbContext>(options =>
{
// Using Pomelo.EntityFrameworkCore.MySql library
options.UseMySql(builder.Configuration.GetConnectionString("EaterMysql"), ServerVersion.Parse("8.0.21-mysql"));
});
在我们的 Repository 中,我们访问 DB 上下文中的 DbSet 字段来执行查询, 在这里,我们使用 LINQ,这是一组直接融入 C# 语言的 API,用于从各种数据源进行查询。这是我非常喜欢的一项功能,因为它提供了 Fluent API,例如 Where()、Include() 或 OrderBy(),这非常方便!
public class ProductOrderRepository : BaseRepository<ProductOrder>, IProductOrderRepository
{
public ProductOrderRepository(AppDbContext context) : base(context)
{
}
public Task<ProductOrder?> GetById(string id) => _context.ProductOrder
.Include(o => o.Customer)
.Include(o => o.Items)
.Where(o => o.Id == id)
.FirstOrDefaultAsync();
public Task<List<ProductOrder>> GetAllByCustomer(Customer customer) => _context.ProductOrder
.Include(o => o.Items)
.Where(o => o.Customer == customer)
.ToListAsync();
public Task<List<ProductOrder>> GetAllByProductId(string productId) => _context.ProductOrder
.Include(o => o.Customer)
.Include(o => o.Items)
.Where(o => o.Items.Any(item => item.ProductId == productId))
.ToListAsync();
}
依赖注入
Spring Boot 中的依赖注入真的非常简单, 只需根据类的角色使用 @Component 、 @Service 或 @Repository 等注解即可,在启动时,它会进行扫描,然后注册。
@Service
class ProductOrderService(
private val customerRepository: ICustomerRepository,
private val productOrderRepository: IProductOrderRepository,
private val mapper: IMapper
) : IProductOrderService {
// ...
// ...
// ...
}
在 .NET Core 中, 服务根据生命周期分成3中类型,单例的,范围的, 瞬时的,并且在启动时手动注册到 DI 容器中
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Services
builder.Services.AddSingleton<IPasswordEncoder, PasswordEncoder>();
builder.Services.AddSingleton<ITokenService, TokenService>();
builder.Services.AddScoped<IProductOrderService, ProductOrderService>();
builder.Services.AddScoped<ICustomerService, CustomerService>();
// Repositories
builder.Services.AddScoped<IProductOrderRepository, ProductOrderRepository>();
builder.Services.AddScoped<ICustomerRepository, CustomerRepository>();
身份验证和授权
在 Spring Boot 中, 首先需要添加依赖
spring-boot-starter-security , 然后,在 build.gradle 文件(或 pom.xml,如果您使用 Maven)中为 JWT 库添加以下依赖项:
implementation("io.jsonwebtoken:jjwt-api:${jjwtVersion}")
implementation("io.jsonwebtoken:jjwt-impl:${jjwtVersion}")
implementation("io.jsonwebtoken:jjwt-jackson:${jjwtVersion}")
接下来, 需要创建一个负责 JWT 令牌解析和验证的过滤器/中间件, 然后重写 doFilterInternal 方法, 编写解析和验证逻辑。
class JwtAuthenticationFilter(
private val tokenService: ITokenService
) : OncePerRequestFilter() {
override fun doFilterInternal(
request: HttpServletRequest,
response: HttpServletResponse,
filterChain: FilterChain
) {
val authorization = request.getHeader("Authorization")
if (authorization == null || !authorization.startsWith("Bearer")) {
return filterChain.doFilter(request, response)
}
val token = authorization.replaceFirst("Bearer ", "")
val claims = try {
tokenService.parse(token).body
} catch (ex: JwtException) {
SecurityContextHolder.clearContext()
return
}
// Set authentication to tell Spring that the user is valid and authenticated.
SecurityContextHolder.getContext().authentication = UsernamePasswordAuthenticationToken(claims.id, null, arrayListOf())
filterChain.doFilter(request, response)
}
}
要配置和强制执行身份验证,需要先创建一个继承
WebSecurityConfigurerAdapter 的配置类,并使用 @Configuration 注解, 在这里注册我们上面创建的 JWT 过滤器,并在 configure 方法中配置哪些端点应该进行身份验证。比如,我允许匿名访问客户登录和注册端点。其他所有内容都应进行身份验证
class ApiAccessDeniedHandler : AccessDeniedHandler {
override fun handle(
request: HttpServletRequest,
response: HttpServletResponse,
accessDeniedException: AccessDeniedException
) {
response.status = HttpStatus.FORBIDDEN.value()
}
}
class AuthEntryPoint : AuthenticationEntryPoint {
override fun commence(
request: HttpServletRequest,
response: HttpServletResponse,
authException: AuthenticationException
) {
response.status = HttpStatus.UNAUTHORIZED.value()
}
}
@Configuration
class SecurityConfig(
tokenService: ITokenService
) : WebSecurityConfigurerAdapter() {
private val jwtAuthenticationFilter = JwtAuthenticationFilter(tokenService)
@Bean
fun passwordEncoder(): PasswordEncoder = BCryptPasswordEncoder()
override fun configure(http: HttpSecurity) {
http.csrf().disable().cors().disable()
.addFilterAfter(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter::class.java)
.exceptionHandling()
.accessDeniedHandler(ApiAccessDeniedHandler())
.authenticationEntryPoint(AuthEntryPoint())
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/v1/customer/register", "/v1/customer/login").permitAll()
.anyRequest().authenticated()
}
}
在 ASP.NET Core 中实现 JWT 身份验证和授权非常简单, 首先安装
Microsoft.AspNetCore.Authentication.JwtBearer` NuGet 包, 然后,在 Program.cs 文件中配置一些设置,例如密钥、颁发者和到期时间。
var builder = WebApplication.CreateBuilder(args);
// Configure JWT Authentication
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.RequireHttpsMetadata = true;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateAudience = false,
ValidIssuer = builder.Configuration["JWT:ValidIssuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JWT:Secret"])),
ClockSkew = TimeSpan.FromSeconds(30)
};
});
var app = builder.Build();
// Enable Authentication & Authorization
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
如果需要认证,就在控制或者方法上,加上 [Authorize] 特性, 同样,可以加上 [AllowAnonymous] 代表允许匿名访问。
[Route("v1/customer")]
[ApiController]
[Authorize]
public class CustomerController : ControllerBase
{
[HttpPost("login")]
[AllowAnonymous]
public async Task<AuthResultDto> Login([FromBody] LoginForm form) => await _customerService.Login(form);
[HttpGet]
public async Task<CustomerDto> GetProfile() => await _customerService.GetProfile();
}
性能
最后是关键的部分,性能, 这两个框架在 QPS 和 内存使用率方面的表现如何?
在这里,我做了一个负载测试,调用一个 API,通过 id 获取一个产品订单。
测试环境
CPU:Intel Core i7–8750H( 4.10 GHz),6 核 12 线程
RAM:32 GB
操作系统:Windows 11
测试设置
我使用的压力测试工具是 K6 , 进行了2次测试, 因为我想看看程序预热后性能提高了多少。在每次测试中,前 30 秒将从 0 增加到 1000 个虚拟用户,然后在那里停留 1 分钟。然后再过 30 秒,测试将从 1000 用户减少到 0 用户。
我还将 Golang(使用 Gin 框架和 Gorm)添加到基准测试, 这里只是为了对比 我们都知道 Golang 非常快。
测试结果
显然,Golang 是最快的,我检查了两者都执行了查询优化,确认没有 N+1 问题,所以在 qps 上 .NET Core 胜出。
在内存使用方面,Golang 当然是最小的(只有 113 MB!),其次是 .NET Core, 最后就是超过1 GB 内存的 Spring Boot, 另外我观察到的有趣的事情是,测试完成后,Golang 和 .NET Core 的内存消耗分别减少到 10 MB 和 100 MB 左右,而 Spring Boot 保持在 1 GB 以上,直到我终止进程。
最后,Spring Boot 和 ASP.NET Core 都是非常成熟的框架,您都可以考虑使用, 希望对您有用!
原文作者:Putu Prema
原文链接: https://medium.com/@
putuprema/spring-boot-vs-asp-net-core-a-showdown-1d38b89c6c2d
相关推荐
- MySQL进阶五之自动读写分离mysql-proxy
-
自动读写分离目前,大量现网用户的业务场景中存在读多写少、业务负载无法预测等情况,在有大量读请求的应用场景下,单个实例可能无法承受读取压力,甚至会对业务产生影响。为了实现读取能力的弹性扩展,分担数据库压...
- 3分钟短文 | Laravel SQL筛选两个日期之间的记录,怎么写?
-
引言今天说一个细分的需求,在模型中,或者使用laravel提供的EloquentORM功能,构造查询语句时,返回位于两个指定的日期之间的条目。应该怎么写?本文通过几个例子,为大家梳理一下。学习时...
- 一文由浅入深带你完全掌握MySQL的锁机制原理与应用
-
本文将跟大家聊聊InnoDB的锁。本文比较长,包括一条SQL是如何加锁的,一些加锁规则、如何分析和解决死锁问题等内容,建议耐心读完,肯定对大家有帮助的。为什么需要加锁呢?...
- 验证Mysql中联合索引的最左匹配原则
-
后端面试中一定是必问mysql的,在以往的面试中好几个面试官都反馈我Mysql基础不行,今天来着重复习一下自己的弱点知识。在Mysql调优中索引优化又是非常重要的方法,不管公司的大小只要后端项目中用到...
- MySQL索引解析(联合索引/最左前缀/覆盖索引/索引下推)
-
目录1.索引基础...
- 你会看 MySQL 的执行计划(EXPLAIN)吗?
-
SQL执行太慢怎么办?我们通常会使用EXPLAIN命令来查看SQL的执行计划,然后根据执行计划找出问题所在并进行优化。用法简介...
- MySQL 从入门到精通(四)之索引结构
-
索引概述索引(index),是帮助MySQL高效获取数据的数据结构(有序),在数据之外,数据库系统还维护者满足特定查询算法的数据结构,这些数据结构以某种方式引用(指向)数据,这样就可以在这些数据结构...
- mysql总结——面试中最常问到的知识点
-
mysql作为开源数据库中的榜一大哥,一直是面试官们考察的重中之重。今天,我们来总结一下mysql的知识点,供大家复习参照,看完这些知识点,再加上一些边角细节,基本上能够应付大多mysql相关面试了(...
- mysql总结——面试中最常问到的知识点(2)
-
首先我们回顾一下上篇内容,主要复习了索引,事务,锁,以及SQL优化的工具。本篇文章接着写后面的内容。性能优化索引优化,SQL中索引的相关优化主要有以下几个方面:最好是全匹配。如果是联合索引的话,遵循最...
- MySQL基础全知全解!超详细无废话!轻松上手~
-
本期内容提醒:全篇2300+字,篇幅较长,可搭配饭菜一同“食”用,全篇无废话(除了这句),干货满满,可收藏供后期反复观看。注:MySQL中语法不区分大小写,本篇中...
- 深入剖析 MySQL 中的锁机制原理_mysql 锁详解
-
在互联网软件开发领域,MySQL作为一款广泛应用的关系型数据库管理系统,其锁机制在保障数据一致性和实现并发控制方面扮演着举足轻重的角色。对于互联网软件开发人员而言,深入理解MySQL的锁机制原理...
- Java 与 MySQL 性能优化:MySQL分区表设计与性能优化全解析
-
引言在数据库管理领域,随着数据量的不断增长,如何高效地管理和操作数据成为了一个关键问题。MySQL分区表作为一种有效的数据管理技术,能够将大型表划分为多个更小、更易管理的分区,从而提升数据库的性能和可...
- MySQL基础篇:DQL数据查询操作_mysql 查
-
一、基础查询DQL基础查询语法SELECT字段列表FROM表名列表WHERE条件列表GROUPBY分组字段列表HAVING分组后条件列表ORDERBY排序字段列表LIMIT...
- MySql:索引的基本使用_mysql索引的使用和原理
-
一、索引基础概念1.什么是索引?索引是数据库表的特殊数据结构(通常是B+树),用于...
- 一周热门
-
-
C# 13 和 .NET 9 全知道 :13 使用 ASP.NET Core 构建网站 (1)
-
程序员的开源月刊《HelloGitHub》第 71 期
-
详细介绍一下Redis的Watch机制,可以利用Watch机制来做什么?
-
假如有100W个用户抢一张票,除了负载均衡办法,怎么支持高并发?
-
如何将AI助手接入微信(打开ai手机助手)
-
Java面试必考问题:什么是乐观锁与悲观锁
-
SparkSQL——DataFrame的创建与使用
-
redission YYDS spring boot redission 使用
-
一文带你了解Redis与Memcached? redis与memcached的区别
-
如何利用Redis进行事务处理呢? 如何利用redis进行事务处理呢英文
-
- 最近发表
- 标签列表
-
- git pull (33)
- git fetch (35)
- mysql insert (35)
- mysql distinct (37)
- concat_ws (36)
- java continue (36)
- jenkins官网 (37)
- mysql 子查询 (37)
- python元组 (33)
- mybatis 分页 (35)
- vba split (37)
- redis watch (34)
- python list sort (37)
- nvarchar2 (34)
- mysql not null (36)
- hmset (35)
- python telnet (35)
- python readlines() 方法 (36)
- munmap (35)
- docker network create (35)
- redis 集合 (37)
- python sftp (37)
- setpriority (34)
- c语言 switch (34)
- git commit (34)