当前位置: 首页 > 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.

相关文章:

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 req…...

WPF+Mvvm 项目入门完整教程(一)

WPF+Mvvm 入门完整教程一 创建项目MvvmLight框架安装完善整个项目的目录结构创建自定义的字体资源下载更新和使用字体资源创建项目 打开VS2022,点击创建新项目,选择**WPF应用(.NET Framework)** 创建一个名称为 CommonProject_DeskTop 的项目,如下图所示:MvvmLight框架安装…...

[解决方法]git上传的项目markdown文件的图片无法显示

应该有不少初学者会遇到这种情况 以下是本人摸索出的解决方法 我使用的是typora&#xff0c;首先设置typora的图片设置 文件>偏好设置>图像 如下&#xff1a; 选择这个就会在此文件的同级目录下创建一个assets文件夹来存放此markdown文件的所有图片 然后勾选优先使用相…...

【React】使用 antd 加载组件实现 iframe 的加载效果

文章目录 代码实现&#xff1a; import { Spin } from antd; import { useState } from react;export default function () {const [loading, setLoading] useState(true);return (<div style{{ position: relative, height: 100% }}><Spinstyle{{ position: absolu…...

Python爬虫(1) --基础知识

爬虫 爬虫是什么&#xff1f; spider 是一种模仿浏览器上网过程的一种程序&#xff0c;可以获取一些网页的数据 基础知识 URL 统一资源定位符 uniform resource locator http: 超文本传输协议 HyperText Transfer Protocol 默认端口 80 https: 安全的超文本传输协议 security…...

云原生系列 - Jenkins

Jenkins Jenkins&#xff0c;原名 Hudson&#xff0c;2011 年改为现在的名字。它是一个开源的实现持续集成的软件工具。 官方网站&#xff08;英文&#xff09;&#xff1a;https://www.jenkins.io/ 官方网站&#xff08;中文&#xff09;&#xff1a;https://www.jenkins.io…...

django踩坑(四):终端输入脚本可正常执行,而加入crontab中无任何输出

使用crontab执行python脚本时&#xff0c;有时会遇到脚本无法执行的问题。这是因为crontab在执行任务时使用的环境变量与我们在终端中使用的环境变量不同。具体来说&#xff0c;crontab使用的环境变量是非交互式(non-interactive)环境变量&#xff0c;而终端则使用交互式(inter…...

计算机网络入门 -- 常用网络协议

计算机网络入门 – 常用网络协议 1.分类 1.1 模型回顾 计算机网络细分可以划为七层模型&#xff0c;分别是物理层、数据链路层、网络层、传输层、会话层、表示层和应用层。而上三层可以划为应用层中。 1.2 分类 1.2.1 应用层 为用户的应用进程提供网络通信服务&#xff0…...

【LabVIEW作业篇 - 4】:属性节点赋值和直接节点赋值的区别体现

文章目录 属性节点赋值和直接节点赋值的区别体现 属性节点赋值和直接节点赋值的区别体现 创建5个圆形指示灯&#xff0c;然后循环点亮&#xff0c;先给圆形指示灯赋值假变量&#xff0c;然后再进行循环。 运行结果&#xff0c;观察结果&#xff0c;发现刚开始运行时&#xff0…...

【数据库系列】Parquet 文件介绍

&#x1f49d;&#x1f49d;&#x1f49d;欢迎来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:kwan 的首页,持续学…...

A Survey on Multimodal Large Language Models综述

论文题目:A Survey on Multimodal Large Language Models 论文地址:https://arxiv.org/pdf/2306.13549 话题:多模态LLMs综述 MLLMs Paper: https://github.com/BradyFU/Awesome-Multimodal-Large-Language-Models 1. 摘要 近期,以GPT-4V为代表的跨模态大型语言模型(MLLM…...

Leetcode3208. 交替组 II

Every day a Leetcode 题目来源&#xff1a;3208. 交替组 II 解法1&#xff1a;环形数组 把数组复制一份拼接起来&#xff0c;和 3101 题一样&#xff0c;遍历数组的同时&#xff0c;维护以 i 为右端点的交替子数组的长度 cnt。 如果 i ≥ n 且 cnt ≥ k&#xff0c;那么 i…...

汇编教程2

本教程主要教大家如何安装32位Linux虚拟机&#xff0c;为后续实验拆炸弹做准备 下载系统映像文件 以Ubuntu14.04.6系统为例 官方网站&#xff1a;下载地址 点击下载图中32位系统 如果官网进不去可以使用镜像网站 清华镜像网站&#xff1a;下载地址 进入之后找到下图中链接…...

使用 git 和 GitHub 互动

本文根据《GitHub入门与实践》整理 创建账户 要想使用GitHub那就必须先有GitHub账号,账号自行注册,不作介绍。 本地生成 SSH Key SSH 提供了一种安全的方式来通过不安全的网络进行通信。当你使用SSH key连接到GitHub时,你的身份是通过密钥对(一个公钥和一个私钥)来验…...

【Spring Boot 中的 `banner.txt` 和 `logback-spring.xml` 配置】

文章目录 一、banner.txt1. 创建自定义 banner.txt2. 配置 banner.txt 的内容 二、logback-spring.xml1. 创建 logback-spring.xml2. 配置 logback-spring.xml 一、banner.txt banner.txt 是 Spring Boot 项目启动时显示的自定义横幅内容。用来展示项目名称、版本信息或者其他…...

Python Linux环境(Centos8)安装minicoda3+jupyterlab

文章目录 安装miniconda安装python环境启动 最近服务器检查&#xff0c;我下面的服务器有漏洞&#xff0c;不得已重装了&#xff0c;正好记录下怎么从零到python写代码。 安装miniconda miniconda是anconda的精简版&#xff0c;就是管理python环境的得力助手。 # 创建一个名…...

Python PDF Magic:合并和拆分随心所欲

大家好&#xff01;小编今天要为大家带来一篇关于Python操作PDF的秘籍——无论是要将PDF合并成一份整体&#xff0c;还是将一个庞大的PDF文件拆分成多个小伙伴&#xff0c;都轻松hold住&#xff01;你准备好了吗&#xff1f;让我们开始这场奇妙的PDF操作之旅吧&#xff01; 准…...

Gmsh应用程序编程接口

Gmsh应用程序编程接口&#xff08;API&#xff09;允许将Gmsh库集成到使用C、C、Python、Julia或Fortran编写的外部应用程序中。从设计上讲&#xff0c;Gmsh API是纯粹功能性的&#xff0c;并且仅使用目标语言的基本类型。 API的结构反映了底层的Gmsh数据模型&#xff08;也请参…...

DP 203 学习笔记

考试内容总览 Learning Objects: 工具 Designing and implementing data storage 1. Storage Azure Synapse Analytics Azure Databricks Azure Data Lake Storage Gen2(ADLS2&#xff0c;可代替Hadoop Distributed File System也就是HDFS) 2. Shard Partition data store …...

SQLite 事务

SQLite 事务 SQLite 是一种轻量级的数据库管理系统,广泛用于各种应用程序中,特别是在移动设备和嵌入式系统中。它支持标准的 SQL 语法,包括事务处理。事务是数据库管理系统中的一个重要概念,它允许将一系列操作作为一个单独的工作单元来处理,以确保数据库的一致性和可靠性…...

Spark 之 入门讲解详细版(1)

1、简介 1.1 Spark简介 Spark是加州大学伯克利分校AMP实验室&#xff08;Algorithms, Machines, and People Lab&#xff09;开发通用内存并行计算框架。Spark在2013年6月进入Apache成为孵化项目&#xff0c;8个月后成为Apache顶级项目&#xff0c;速度之快足见过人之处&…...

React hook之useRef

React useRef 详解 useRef 是 React 提供的一个 Hook&#xff0c;用于在函数组件中创建可变的引用对象。它在 React 开发中有多种重要用途&#xff0c;下面我将全面详细地介绍它的特性和用法。 基本概念 1. 创建 ref const refContainer useRef(initialValue);initialValu…...

基于ASP.NET+ SQL Server实现(Web)医院信息管理系统

医院信息管理系统 1. 课程设计内容 在 visual studio 2017 平台上&#xff0c;开发一个“医院信息管理系统”Web 程序。 2. 课程设计目的 综合运用 c#.net 知识&#xff0c;在 vs 2017 平台上&#xff0c;进行 ASP.NET 应用程序和简易网站的开发&#xff1b;初步熟悉开发一…...

多模态商品数据接口:融合图像、语音与文字的下一代商品详情体验

一、多模态商品数据接口的技术架构 &#xff08;一&#xff09;多模态数据融合引擎 跨模态语义对齐 通过Transformer架构实现图像、语音、文字的语义关联。例如&#xff0c;当用户上传一张“蓝色连衣裙”的图片时&#xff0c;接口可自动提取图像中的颜色&#xff08;RGB值&…...

对WWDC 2025 Keynote 内容的预测

借助我们以往对苹果公司发展路径的深入研究经验&#xff0c;以及大语言模型的分析能力&#xff0c;我们系统梳理了多年来苹果 WWDC 主题演讲的规律。在 WWDC 2025 即将揭幕之际&#xff0c;我们让 ChatGPT 对今年的 Keynote 内容进行了一个初步预测&#xff0c;聊作存档。等到明…...

CRMEB 框架中 PHP 上传扩展开发:涵盖本地上传及阿里云 OSS、腾讯云 COS、七牛云

目前已有本地上传、阿里云OSS上传、腾讯云COS上传、七牛云上传扩展 扩展入口文件 文件目录 crmeb\services\upload\Upload.php namespace crmeb\services\upload;use crmeb\basic\BaseManager; use think\facade\Config;/*** Class Upload* package crmeb\services\upload* …...

06 Deep learning神经网络编程基础 激活函数 --吴恩达

深度学习激活函数详解 一、核心作用 引入非线性:使神经网络可学习复杂模式控制输出范围:如Sigmoid将输出限制在(0,1)梯度传递:影响反向传播的稳定性二、常见类型及数学表达 Sigmoid σ ( x ) = 1 1 +...

.Net Framework 4/C# 关键字(非常用,持续更新...)

一、is 关键字 is 关键字用于检查对象是否于给定类型兼容,如果兼容将返回 true,如果不兼容则返回 false,在进行类型转换前,可以先使用 is 关键字判断对象是否与指定类型兼容,如果兼容才进行转换,这样的转换是安全的。 例如有:首先创建一个字符串对象,然后将字符串对象隐…...

AI病理诊断七剑下天山,医疗未来触手可及

一、病理诊断困局&#xff1a;刀尖上的医学艺术 1.1 金标准背后的隐痛 病理诊断被誉为"诊断的诊断"&#xff0c;医生需通过显微镜观察组织切片&#xff0c;在细胞迷宫中捕捉癌变信号。某省病理质控报告显示&#xff0c;基层医院误诊率达12%-15%&#xff0c;专家会诊…...

协议转换利器,profinet转ethercat网关的两大派系,各有千秋

随着工业以太网的发展&#xff0c;其高效、便捷、协议开放、易于冗余等诸多优点&#xff0c;被越来越多的工业现场所采用。西门子SIMATIC S7-1200/1500系列PLC集成有Profinet接口&#xff0c;具有实时性、开放性&#xff0c;使用TCP/IP和IT标准&#xff0c;符合基于工业以太网的…...