当前位置: 首页 > news >正文

Springboot 3.x - Reactive programming (2)

三、WebFlux

Blocking Web vs. Reactive Web

Blocking Web (Servlet) and Reactive Web (WebFlux) have significant differences in several aspects.

1. Front Controller
  • Servlet-Blocking Web: Uses DispatcherServlet as the front controller to handle all HTTP requests.
  • WebFlux-Reactive Web: Uses DispatcherHandler as the front controller to handle all HTTP requests.
2. Handler
  • Servlet-Blocking Web: Uses Controller as the handler.
  • WebFlux-Reactive Web: Uses WebHandler or Controller as the handler.
3. Request and Response
  • Servlet-Blocking Web: Uses ServletRequest and ServletResponse.
  • WebFlux-Reactive Web: Uses ServerWebExchange, along with ServerRequest and ServerResponse.
4. Filters
  • Servlet-Blocking Web: Uses Filter (e.g., HttpFilter).
  • WebFlux-Reactive Web: Uses WebFilter.
5. Exception Handlers
  • Servlet-Blocking Web: Uses HandlerExceptionResolver to handle exceptions.
  • WebFlux-Reactive Web: Uses DispatchExceptionHandler to handle exceptions.
6. Web Configuration
  • Servlet-Blocking Web: Configured via @EnableWebMvc.
  • WebFlux-Reactive Web: Configured via @EnableWebFlux.
7. Custom Configuration
  • Servlet-Blocking Web: Uses WebMvcConfigurer.
  • WebFlux-Reactive Web: Uses WebFluxConfigurer.
8. Return Types
  • Servlet-Blocking Web: The return type can be any object.
  • WebFlux-Reactive Web: The return type can be a Mono, a Flux, or any object.
9. Sending REST Requests
  • Servlet-Blocking Web: Uses RestTemplate to send REST requests.
  • WebFlux-Reactive Web: Uses WebClient to send REST requests.
Core Difference Between Blocking and Reactive Models

Blocking Model (Servlet): Each request is handled by a dedicated thread, which waits for operations to complete (such as database queries or IO operations). This model can lead to thread exhaustion under high concurrency, affecting system performance.

Reactive Model (WebFlux): Uses a non-blocking IO model with a small number of threads handling many requests. It leverages callback mechanisms, event-driven architecture, and asynchronous non-blocking IO for efficient resource utilization and high concurrency handling. Key features of the reactive programming model include:

  • Non-blocking Operations: Operations do not block the current thread, allowing it to continue processing other tasks.
  • Callback Mechanism: Handles subsequent steps through callback mechanisms once an operation completes.
  • Event-driven Architecture: Processes requests based on an event-driven approach.

This model is more efficient in resource usage and is suitable for scenarios requiring high concurrency and large traffic volumes.

Summary

The choice between a blocking or reactive web framework depends on specific application scenarios and requirements. If the application is primarily I/O-intensive with high concurrency needs, then WebFlux is a more suitable choice; if it involves CPU-intensive tasks, the traditional Servlet model might be more appropriate.

四、Integration with Springboot

Spring WebFlux is the new reactive web framework introduced in Spring Framework 5.0. Unlike Spring MVC, it does not require the servlet API, is fully asynchronous and non-blocking, and implements the Reactive Streams specification through the Reactor project.

Spring WebFlux comes in two flavors: functional and annotation-based. The annotation-based one is quite close to the Spring MVC model, as shown in the following example:

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/users")
public class MyRestController {private final UserRepository userRepository;private final CustomerRepository customerRepository;public MyRestController(UserRepository userRepository, CustomerRepository customerRepository) {this.userRepository = userRepository;this.customerRepository = customerRepository;}@GetMapping("/{userId}")public Mono<User> getUser(@PathVariable Long userId) {return this.userRepository.findById(userId);}@GetMapping("/{userId}/customers")public Flux<Customer> getUserCustomers(@PathVariable Long userId) {return this.userRepository.findById(userId).flatMapMany(this.customerRepository::findByUser);}@DeleteMapping("/{userId}")public Mono<Void> deleteUser(@PathVariable Long userId) {return this.userRepository.deleteById(userId);}}

“WebFlux.fn”, the functional variant, separates the routing configuration from the actual handling of the requests, as shown in the following example:

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.RequestPredicate;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;import static org.springframework.web.reactive.function.server.RequestPredicates.accept;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;/*** <B>Main class name:</B>MyRoutingConfiguration<BR>* <B>Summary description:</B>WebFlux router configuration class<BR>* @author Chris.Gou* @since 2024/07/19 14:53:40*/
@SpringBootConfiguration(proxyBeanMethods = false)
public class MyRoutingConfiguration {/*** RequestPredicate is an interface that defines a request predicate, that is, a condition for testing HTTP requests. <BR/>* Here, ACCEPT_JSON defines a predicate that checks whether the Accept header of the request is application/json.*/private static final RequestPredicate ACCEPT_JSON = accept(MediaType.APPLICATION_JSON);/*** RouterFunction<ServerResponse> is an interface that represents a routing function that routes a request to a handler and returns a ServerResponse.* @param userHandler* @return*/@Beanpublic RouterFunction<ServerResponse> monoRouterFunction(MyUserHandler userHandler) {return route() // route() is a static method that returns a RouterFunctions.Builder for building routing functions..GET("/{user}", ACCEPT_JSON, userHandler::getUser).GET("/{user}/customers", ACCEPT_JSON, userHandler::getUserCustomers).DELETE("/{user}", ACCEPT_JSON, userHandler::deleteUser).build();}}
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;/*** <B>Main class name:</B>MyUserHandler<BR>* <B>Summary description:</B>MyUserHandler<BR>* @author Chris.Gou* @since 2024/07/19 15:02:47*/
@Component
public class MyUserHandler {public Mono<ServerResponse> getUser(ServerRequest request) {// Business processingreturn null;}public Mono<ServerResponse> getUserCustomers(ServerRequest request) {// Business processingreturn null;}public Mono<ServerResponse> deleteUser(ServerRequest request) {// Business processingreturn null;}
}

These route definitions enable applications to implement specific business logic by routing requests to corresponding handler methods based on different URL patterns and HTTP methods.

http://www.lryc.cn/news/403146.html

相关文章:

  • WPF+Mvvm 项目入门完整教程(一)
  • [解决方法]git上传的项目markdown文件的图片无法显示
  • 【React】使用 antd 加载组件实现 iframe 的加载效果
  • Python爬虫(1) --基础知识
  • 云原生系列 - Jenkins
  • django踩坑(四):终端输入脚本可正常执行,而加入crontab中无任何输出
  • 计算机网络入门 -- 常用网络协议
  • 【LabVIEW作业篇 - 4】:属性节点赋值和直接节点赋值的区别体现
  • 【数据库系列】Parquet 文件介绍
  • A Survey on Multimodal Large Language Models综述
  • Leetcode3208. 交替组 II
  • 汇编教程2
  • 使用 git 和 GitHub 互动
  • 【Spring Boot 中的 `banner.txt` 和 `logback-spring.xml` 配置】
  • Python Linux环境(Centos8)安装minicoda3+jupyterlab
  • Python PDF Magic:合并和拆分随心所欲
  • Gmsh应用程序编程接口
  • DP 203 学习笔记
  • SQLite 事务
  • LabVIEW和Alicat Scientific质量流量计实现精确流量控制
  • 2024-07-19 Unity插件 Odin Inspector10 —— Misc Attributes
  • Go操作Redis详解
  • 钡铼Modbus TCP耦合器BL200实现现场设备与SCADA无缝对接
  • 数据分析入门:用Python和Numpy探索音乐流行趋势
  • 数仓工具—Hive语法之替换函数和示例
  • [SUCTF 2019]EasySQL1
  • elasticsearch, kibana, 6.8.18 版本下的创建索引,指定timestamp,java CRUD,maven版本等
  • 无人机侦察:二维机扫雷达探测设备技术详解
  • 未来互联网的新篇章:深度解析Web3技术
  • vst 算法R语言手工实现 | Seurat4 筛选高变基因的算法