欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 维修 > 深入解析 Spring WebFlux:原理与应用

深入解析 Spring WebFlux:原理与应用

2025/2/23 23:40:56 来源:https://blog.csdn.net/rgrgrwfe/article/details/144789410  浏览:    关键词:深入解析 Spring WebFlux:原理与应用

优质博文:IT-BLOG-CN

WebFlux 是 Spring Framework 5 引入的一种响应式编程框架,和Spring MVC同级,旨在处理高并发和低延迟的非阻塞应用。这是一个支持反应式编程模型的新Web框架体系。 顺便一提,Spring Cloud Gateway在实现上是对Spring WebFlux的拓展。

一、WebFlux 的基本原理

响应式编程模型: WebFlux 基于 Reactor 库,采用响应式编程模型。它使用 Mono 和 Flux 作为基本构建块,分别表示 0-1 个元素和 0-N 个元素的异步序列。

非阻塞 IO: WebFlux 使用非阻塞 IO(NIO)来处理请求,这意味着线程不会因为等待 IO 操作而被阻塞,从而提高了资源利用率和应用的吞吐量。

背压机制: WebFlux 支持背压(Backpressure),即在数据生产者和消费者之间建立一种反馈机制,确保生产者不会压垮消费者。

请求处理调用链
在这里插入图片描述

二、WebFlux 的核心组件

HandlerFunction 和 RouterFunction
HandlerFunction:处理请求的函数式接口,类似于 Spring MVC 中的 @Controller。
RouterFunction:定义路由的函数式接口,类似于 Spring MVC 中的 @RequestMapping。

WebClient: WebClient 是 WebFlux 提供的一个非阻塞的、响应式的 HTTP 客户端,用于发起 HTTP 请求并处理响应。

看完源码回过头来看文档,发现DispatcherHandler的介绍文档就说明了这些比较重要的组件了。

Spring WebFlux, similarly to Spring MVC, is designed around the front controller pattern, where a central WebHandler, the DispatcherHandler, provides a shared algorithm for request processing, while actual work is performed by configurable, delegate components.

spring webflux 类似于Spring MVC,围绕前端controller模式————a central WebHandler,即DispatcherHandler(对请求提供一系列通用计算处理方式,并让一些相关职责的可配置组件执行处理) 。

Spring configuration in a WebFlux application typically contains:
1、DispatcherHandler with the bean name, webHandler
2、WebFilter and WebExceptionHandler beans
3、DispatcherHandler special beans
4、Others

DispatcherHandler: 默认核心WebHandler。 核心方法:

public Mono<Void> handle(ServerWebExchange exchange) {if (this.handlerMappings == null) {return createNotFoundError();}return Flux.fromIterable(this.handlerMappings).concatMap(mapping -> mapping.getHandler(exchange)).next().switchIfEmpty(createNotFoundError()).flatMap(handler -> invokeHandler(exchange, handler)).flatMap(result -> handleResult(exchange, result));
}

HandlerMapping 匹配请求与handler的关系,根据请求获得对应处理handler
HandlerAdapter 执行Handler,返回HandlerResult
HandlerResultHandler 处理HandlerResult

举例说下,具体到常用的注解声明的@RequestMapping, 首先,会在requestMapping中找到对应的HandlerMethod(可关注下该方法AbstractHandlerMethodMapping.lookupHandlerMethod(ServerWebExchange exchange))
然后,通过对应的能支持HandlerMethod的HandlerAdapter执行具体方法处理,得到HandlerResult
最后,匹配到能处理该HandlerResult的HandlerResultHandler,结果处理

HttpHandler: 一般用来组合出ServerWebExchange类,默认实现HttpWebHandlerAdapter还做了执行目标webHandler(DispatcherHandler)的操作。

三、WebFlux 的应用场景

高并发应用: WebFlux 非阻塞的特性使其非常适合高并发场景,如实时数据流处理、在线游戏服务器等。

微服务架构: 在微服务架构中,服务之间的通信通常需要高效的 HTTP 客户端,WebClient 提供了一个理想的选择。

数据流处理: WebFlux 可以与 Reactor 结合使用,处理数据流应用,如实时数据分析、事件驱动系统等。

示例代码: 基本路由和处理器

@Configuration
public class RouterConfig {@Beanpublic RouterFunction<ServerResponse> route() {return RouterFunctions.route(RequestPredicates.GET("/hello"), this::helloHandler);}private Mono<ServerResponse> helloHandler(ServerRequest request) {return ServerResponse.ok().body(BodyInserters.fromValue("Hello, WebFlux!"));}
}

使用 WebClient 发起请求

WebClient webClient = WebClient.create("http://example.com");Mono<String> response = webClient.get().uri("/api/data").retrieve().bodyToMono(String.class);response.subscribe(System.out::println);

性能优化: 使用连接池,配置连接池以复用连接,减少连接建立和释放的开销。调整线程模型,根据应用的负载和特性,调整线程池的大小和策略,以优化资源使用。

常见问题与解决方案: 阻塞操作,确保在响应式链中没有阻塞操作,必要时可以使用 Schedulers.boundedElastic() 切换到弹性线程池。

错误处理: 使用 onErrorResume 或 onErrorReturn 进行错误处理,确保应用的健壮性。

webflux应用启动简单流程整理,列出了reactive applicationContext相关的启动流程,及几个重要的bean的初始化。 图中做了一些辅助性解释,可对照上面请求执行流程看下。
在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词