IT评测·应用市场-qidao123.com

标题: Spring Boot Web技术栈(官网文档解读) [打印本页]

作者: 愛在花開的季節    时间: 2025-1-15 04:15
标题: Spring Boot Web技术栈(官网文档解读)
摘要   

        Spring Boot框架既支持传统的Servlet技术栈,也支持新兴的响应式(Reactive)技术栈。本篇文章将详细报告Spring Boot 对两种技术栈的详细支持和使用。
Servlet

概述

        基于Java Servlet API构建,它依赖于传统的阻塞I/O模子,每个HTTP哀求都会分配一个线程来处理,直到响应返回给客户端。这种模子适用于大多数传统的Web应用,其中大部分操作是同步的,而且涉及到数据库查询或文件读写等I/O密集型任务。

Spring Boot 对Servlet技术栈的实现架构

Spring MVC

简介

        Spring MVC 是 Spring Framework 的核心组件之一,专为构建基于 Servlet 技术的 Web 应用程序而计划。Spring Boot 整合了 Spring MVC 框架,以此提供对传统 Web Servlet 技术栈的全面支持,使得开辟者能够便捷地构建和运行基于 Servlet 的 Web 应用。
实现方式

        添加依赖Spring-boot-starter-web。Spring Boot 默认使用Servlet 技术栈的Spring MVC 架构。
  1. <dependency>
  2.     <groupId>org.springframework.boot</groupId>
  3.     <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>
复制代码
        官网提供了两种实现Spring MVC 架构的示例。第一种是常见的采用 @Controller 或 @RestController 注解的实现方式。
  1. package person.wend.springbootlearnexample.controller;
  2. import org.springframework.web.bind.annotation.*;
  3. @RestController
  4. @RequestMapping("/users")
  5. public class MyRestController {
  6.     @GetMapping("/{userId}")
  7.     public void getUser(@PathVariable Long userId) {
  8.         System.out.println("userId = " + userId);
  9.     }
  10.     @GetMapping("/{userId}/customers")
  11.     public void getUserCustomers(@PathVariable Long userId) {
  12.         System.out.println("userId = " + userId);
  13.     }
  14.     @DeleteMapping("/{userId}")
  15.     public void deleteUser(@PathVariable Long userId) {
  16.         System.out.println("userId = " + userId);
  17.     }
  18. }
复制代码
        第二种是基于函数式编程的初始化设置路由的方式。
  1. package person.wend.springbootlearnexample.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.http.MediaType;
  5. import org.springframework.web.servlet.function.RequestPredicate;
  6. import org.springframework.web.servlet.function.RouterFunction;
  7. import org.springframework.web.servlet.function.ServerResponse;
  8. import static org.springframework.web.servlet.function.RequestPredicates.accept;
  9. import static org.springframework.web.servlet.function.RouterFunctions.route;
  10. @Configuration(proxyBeanMethods = false)
  11. public class MyRountingConfig {
  12.     private static final RequestPredicate ACCEPT_JSON = accept(MediaType.APPLICATION_JSON);
  13.     @Bean
  14.     public RouterFunction<ServerResponse> routerFunction(MyUserHandler userHandler) {
  15.         return route()
  16.                 .GET("/{user}", ACCEPT_JSON, userHandler::getUser)
  17.                 .GET("/{user}/customers", ACCEPT_JSON, userHandler::getUserCustomers)
  18.                 .DELETE("/{user}", ACCEPT_JSON, userHandler::deleteUser)
  19.                 .build();
  20.     }
  21. }
复制代码
  1. package person.wend.springbootlearnexample.config;
  2. import org.springframework.stereotype.Component;
  3. import org.springframework.web.servlet.function.ServerRequest;
  4. import org.springframework.web.servlet.function.ServerResponse;
  5. @Component
  6. public class MyUserHandler {
  7.     public ServerResponse getUser(ServerRequest request) {
  8.         System.out.println("request = " + request);
  9.         return ServerResponse.ok().body("getUser");
  10.     }
  11.     public ServerResponse getUserCustomers(ServerRequest request) {
  12.         System.out.println("request = " + request);
  13.         return ServerResponse.ok().body("getUserCustomers");
  14.     }
  15.     public ServerResponse deleteUser(ServerRequest request) {
  16.         System.out.println("request = " + request);
  17.         return ServerResponse.ok().body("deleteUser");
  18.     }
  19. }
复制代码
主动装配Spring MVC

        Spring Boot 为 Spring MVC 提供了主动设置功能,该功能适用于大多数应用程序。它取代了对 @EnableWebMvc 的需求,而且两者不能同时使用。除了 Spring MVC 的默认设置之外,主动设置还提供了以下特性:
        如果您想要保存 Spring Boot 的这些 MVC 自界说特性,并进行更多的 MVC 自界说操作(如拦截器、格式化器、视图控制器以及其他功能),您可以添加自己的 @Configuration 类,其类型为 WebMvcConfigurer,但不要使用 @EnableWebMvc。
        如果您想要提供 RequestMappingHandlerMapping、RequestMappingHandlerAdapter 或 ExceptionHandlerExceptionResolver 的自界说实例,同时又想保存 Spring Boot 的 MVC 自界说特性,可以声明一个类型为 WebMvcRegistrations 的 Bean,并使用它来提供这些组件的自界说实例。这些自界说实例将担当 Spring MVC 的进一步初始化和设置。如果您想加入并在需要时覆盖后续的处理过程,可以使用 WebMvcConfigurer。
        如果您不想使用主动设置,而且想要完全掌控 Spring MVC,可以添加自己的、带有 @EnableWebMvc 注解的 @Configuration 类。或者,按照 @EnableWebMvc 的 API 文档中描述的那样,添加自己的带有 @Configuration 注解的 DelegatingWebMvcConfiguration。
Jersey

        Jersey 是一个开源的、用于构建 RESTful Web 服务的框架,它是 Java API for RESTful Web Services(JAX-RS)的参考实现。它提供了一组强大的工具和 API,使开辟人员能够轻松地创建、部署和管理 RESTful 服务。
Spring Boot 集成 Jersey

添加依赖

  1. <dependency>
  2.             <groupId>org.springframework.boot</groupId>
  3.             <artifactId>spring-boot-starter-jersey</artifactId>
  4. </dependency>
复制代码
注册端点

  1. package person.wend.springbootlearnexample.config;
  2. import org.glassfish.jersey.server.ResourceConfig;
  3. import org.springframework.stereotype.Component;
  4. import person.wend.springbootlearnexample.controller.JerseyController;
  5. import person.wend.springbootlearnexample.controller.UserJerseyController;
  6. @Component
  7. public class MyJerseyConfig extends ResourceConfig {
  8.     public MyJerseyConfig() {
  9.         register(JerseyController.class);
  10.         register(UserJerseyController.class);
  11.     }
  12. }
复制代码
Jersey 基于 JAX-RS 标准

        Jersey 遵循 JAX-RS 规范,这意味着它提供了标准的注解和 API 来开辟 RESTful Web 服务。例如,使用 @Path 注解来界说资源的 URI 路径,@GET、@POST、@PUT、@DELETE 等注解来界说 HTTP 方法。以下是一个简单的示例:
  1. import javax.ws.rs.GET;
  2. import javax.ws.rs.Path;
  3. import javax.ws.rs.Produces;
  4. import javax.ws.rs.core.MediaType;
  5. @Path("/hello")
  6. public class HelloResource {
  7.     @GET
  8.     @Produces(MediaType.TEXT_PLAIN)
  9.     public String sayHello() {
  10.         return "Hello, World!";
  11.     }
  12. }
复制代码
在上述代码中:

强大的哀求和响应处理

        Jersey 支持多种媒体类型的哀求和响应处理,包括 JSON、XML、HTML、纯文本等。通过 @Consumes 和 @Produces 注解可以指定哀求和响应的数据类型。例如:
  1. import javax.ws.rs.Consumes;
  2. import javax.ws.rs.GET;
  3. import javax.ws.rs.POST;
  4. import javax.ws.rs.Path;
  5. import javax.ws.rs.Produces;
  6. import javax.ws.rs.core.MediaType;
  7. import javax.ws.rs.core.Response;
  8. @Path("/user")
  9. public class UserResource {
  10.     @GET
  11.     @Produces(MediaType.APPLICATION_JSON)
  12.     public User getUser() {
  13.         User user = new User("John", 30);
  14.         return user;
  15.     }
  16.     @POST
  17.     @Consumes(MediaType.APPLICATION_JSON)
  18.     @Produces(MediaType.APPLICATION_JSON)
  19.     public Response createUser(User user) {
  20.         // 处理用户创建逻辑
  21.         return Response.status(Response.Status.CREATED).entity(user).build();
  22.     }
  23. }
复制代码

Spring Boot 对Servlet 技术栈的嵌入式容器支持

        当您希望采用传统的Servlet栈来构建应用时,您需要添加spring-boot-starter-web依赖,该依赖默认集成了spring-boot-starter-tomcat,意味着您的应用将使用Tomcat作为Web容器。别的,Spring Boot还支持使用Jetty和Undertow作为可选的Web容器。
 Spring Boot 更换容器示例

        以下是一个使用jetty 更换默认的tomcat 的Maven 依赖设置示例。
  1. <dependency>
  2.         <groupId>org.springframework.boot</groupId>
  3.         <artifactId>spring-boot-starter-web</artifactId>
  4.         <exclusions>
  5.                 <!-- Exclude the Tomcat dependency -->
  6.                 <exclusion>
  7.                         <groupId>org.springframework.boot</groupId>
  8.                         <artifactId>spring-boot-starter-tomcat</artifactId>
  9.                 </exclusion>
  10.         </exclusions>
  11. </dependency>
  12. <!-- Use Jetty instead -->
  13. <dependency>
  14.         <groupId>org.springframework.boot</groupId>
  15.         <artifactId>spring-boot-starter-jetty</artifactId>
  16. </dependency>
复制代码
Reactive

概述

        Reactive 引入了非阻塞I/O模子和变乱驱动架构,旨在进步系统的可伸缩性和响应能力。它答应应用程序以异步方式处理哀求,从而可以在更少的线程上处理更多的并发连接。这使得Reactive Stack非常适合构建微服务架构下的高性能Web服务。

实现方式


  1. <dependency>
  2.             <groupId>org.springframework.boot</groupId>
  3.             <artifactId>spring-boot-starter-webflux</artifactId>
  4. </dependency>
复制代码

  1. @SpringBootApplication
  2. public class SpringBootLearnExampleApplication {
  3.     public static void main(String[] args) {
  4.         SpringApplication springApplication = new SpringApplication(SpringBootLearnExampleApplication.class);
  5.         // 将应用设置为响应式应用
  6.         springApplication.setWebApplicationType(WebApplicationType.REACTIVE);
  7.         SpringApplication.run(SpringBootLearnExampleApplication.class, args);
  8.     }
  9. }
复制代码

Spring WebFlux 主动装配

      Spring WebFlux的主动装配与 Spring MVC 的主动装配过程和功能均保持同等,需要留意的是关于WebFlux 自界说注解与MVC 框架不同等。好比如果您希望保存 Spring Boot 对 WebFlux 的这些自界说设置,同时进行更多的 WebFlux 自界说设置(如添加拦截器、自界说格式化器、设置视图控制器等其他功能),可以添加自界说的 @Configuration 类,使其实现 WebFluxConfigurer 接口,但不要使用 @EnableWebFlux 注解。
Spring Boot 对Reactive 技术栈的嵌入式容器支持

        WebFlux默认采用Netty作为其网络通讯框架。不过,您也可以选择设置Tomcat、Jetty或Undertow来替换Netty作为WebFlux的底层传输层。
Servlet Stack 与 Reactive Stack  比较

  特性
  Servlet Stack
  Reactive Stack
  编程模子
  同步
  异步
  线程管理
  线程池
  轻量级线程/协程
  I/O模子
  阻塞I/O
  非阻塞I/O
  性能优化
  适用于中等规模并发
  适用于大规模并发
  生态系统
  成熟稳固
  相对年轻
  Web容器
  Servlet容器(如Tomcat, Jetty)
  非阻塞服务器(如Netty)
  数据流处理
  可以实现但较为复杂
  内置支持
  示例框架
  Spring MVC,Jersey 
  Spring WebFlux
  优雅关机

           默认情况下,全部四个嵌入式 Web 服务器(Jetty、Reactor Netty、Tomcat 和 Undertow)以及反应式和基于 servlet 的 Web 应用程序均启用了优雅关闭。优雅关闭是关闭应用程序上下文的一部分,在制止SmartLifecyclebean 的最早阶段执行。此制止处理使用超时,提供宽限期,在此期间答应完成现有哀求,但不答应新哀求。
            要设置超时时间,请设置spring.lifecycle.timeout-per-shutdown-phase属性,如以下示例所示:
     spring.lifecycle.timeout-per-shutdown-phase=20s
    在宽限期内拒绝哀求

        不答应新哀求的详细方式取决于所使用的 Web 服务器。实现大概会在网络层制止担当哀求,或者它们大概会返回带有特定 HTTP 状态代码或 HTTP 标头的响应。使用持久连接也可以改变制止担当哀求的方式。Jetty、Reactor Netty 和 Tomcat 将制止在网络层担当新哀求。Undertow 将担当新连接,但会立刻响应服务不可用 (503)。以下是四种Web 服务器的优雅关闭API 接口详情:
TomcatWebServer (Spring Boot 3.4.1 API)
NettyWebServer (Spring Boot 3.4.1 API)
JettyWebServer (Spring Boot 3.4.1 API)
UndertowWebServer (Spring Boot 3.4.1 API)
禁用优雅关机

   server.shutdown=immediate
  参考文献

Servlet Web Applications :: Spring Boot

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/) Powered by Discuz! X3.4