WebFlux
WebFlux介绍
The original web framework included in the Spring Framework, Spring Web MVC, was purpose-built for the Servlet API and Servlet containers. The reactive-stack web framework, Spring WebFlux, was added later in version 5.0. It is fully non-blocking, supports Reactive Streams back pressure, and runs on such servers as Netty, Undertow, and Servlet 3.1+ containers.
- 是 Spring5 新添加的模块,用于 web 开发,功能和 SpringMVC 类似,Webflux 使用当前比较流行的响应式编程的框架。
- 使用传统 web 框架,比如 SpringMVC,这些基于 Servlet 容器,Webflux 是一种异步非阻塞的框架,异步非阻塞的框架在 Servlet3.1 以后才支持,也可以运行在Netty,Undertow,核心是基于 Reactor 的相关 API 实现 的。
-
Webflux 特点
- 异步非阻塞:在有限资源下,提高系统吞吐量和伸缩性,以 Reactor 为基础实现响应式编程
- 函数式编程:Spring5 框架基于 java8,Webflux 使用 Java8 函数式编程方式实现路由请求
-
与SpringMVC的比较
- 两个框架都使用相同的注解方式,都可以运行在 Tomet、Jetty 等容器中
- SpringMVC采用命令式编程,WebFlux采用异步响应式编程
-
使用场景
Spring WebFlux 是一个异步非阻塞式的 Web 框架,所以,它特别适合应用在 IO 密集型的服务中,比如微服务网关这样的应用中。
PS: IO 密集型包括:磁盘IO密集型, 网络IO密集型,微服务网关就属于网络 IO 密集型,使用异步非阻塞式编程模型,能够显著地提升网关对下游服务转发的吞吐量。
-
选 WebFlux 还是 Spring MVC
首先需要明确一点就是:WebFlux 不是 Spring MVC 的替代方案!,虽然 WebFlux 也可以被运行在 Servlet 容器上(需是 Servlet 3.1+ 以上的容器),但是 WebFlux 主要还是应用在异步非阻塞编程模型,而 Spring MVC 是同步阻塞的,如果你目前在 Spring MVC 框架中大量使用非同步方案,那么,WebFlux 才是你想要的,否则,使用 Spring MVC 才是你的首选。
响应式编程
响应式编程是一种面向数据流和变化传播的编程范式。这意味着可以在编程语言中很方便地表达静态或动态的数据流,而相关的计算模型会自动将变化的值通过数据流进行传播。
电子表格程序就是响应式编程的一个例子。 单元格可以包含字面值或类似 “=B1+C1” 的公式,而包含公式的单元格的值会依据其他单元格的值的变化而变化。
Java8及其之前的版本实现
提供的观察者模式两个类 Observer 和 Observable
|
|
Reactor实现
-
响应式编程操作中,Reactor 是满足 Reactive 规范的框架,webflux的核心就是基于Reactor框架实现的
-
Reactor 有两个核心类,Mono 和 Flux,这两个类实现接口 Publisher,提供丰富操作 符。Flux 对象实现发布者,返回 N 个元素;Mono 实现发布者,返回 0 或者 1 个元素
-
Flux 和 Mono 都是数据流的发布者,使用 Flux 和 Mono 都可以发出三种数据信号:元素值,错误信号,完成信号,错误信号和完成信号都代表终止信号,终止信号用于告诉订阅者数据流结束了,错误信号终止数据流同时把错误信息传递给订阅者
-
代码演示
-
引入依赖
1 2 3 4 5 6
<!--引入reactor依赖--> <dependency> <groupId>io.projectreactor</groupId> <artifactId>reactor-core</artifactId> <version>3.3.10.RELEASE</version> </dependency>
-
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
package com.eh.webflux.reactor; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; public class ReactorDemo { public static void main(String[] args) { // just方法直接声明 Flux.just(1, 2, 3).subscribe(System.out::println); Mono.just(4).subscribe(System.out::println); // 数组 Integer[] array = {1, 2, 3, 4}; Flux.fromArray(array); // 集合 List<Integer> list = Arrays.asList(array); Flux.fromIterable(list); // 流 Stream<Integer> stream = list.stream(); Flux.fromStream(stream); } }
-
-
三种信号特点
- 错误信号和完成信号都是终止信号,不能共存的
- 如果没有发送任何元素值,而是直接发送错误或者完成信号,表示是空数据流
- 如果没有错误信号,没有完成信号,表示是无限数据流
-
调用 just 或者其他方法只是声明数据流,数据流并没有发出,只有进行订阅之后才会触 发数据流,不订阅什么都不会发生的
1 2
Flux.just(1, 2, 3).subscribe(System.out::println); Mono.just(4).subscribe(System.out::println);
-
操作符
对数据流进行一道道操作,成为操作符,可以类比工厂流水线。
- map 元素映射为新元素
- flatmap 把流中的每个元素转换成流,并且把转换之后的多个流合并成一个大流。
WebFlux执行流程和核心API
SpringWebflux 基于 Reactor,默认使用容器是 Netty,Netty 是高性能的 基于异步事件驱动的NIO 框架
SpringWebflux 执行过程和 SpringMVC 非常相似,只是实现的组件不一样。springmvc的核心控制器是DispatcherServlet,webflux的核心控制器是DispatchHandler,实现接口 WebHandler
将spring-boot-starter依赖改成依赖spring-boot-starter-webflux,
|
|
spring-boot-starter-webflux依赖spring-boot-starter,如下图
现在可以查看WebHandler接口
|
|
实现类:
其中DispatcherHandler实现方法:
|
|
与springmvc类似,除了DispatcherHandler核心控制器外,还有以下组件:
- HandlerMapping:映射要处理的方法
- HandlerAdapter:请求处理
- HandlerResultHandler:响应结果处理
SpringWebFlux实现函数式编程有两个重要的接口:
- RouterFunction:将请求转发给对应的Handler
- HandlerFunction:处理请求并响应
基于注解实现WebFlux
-
SpringMVC 方式实现,同步阻塞的方式,基于 SpringMVC+Servlet+Tomcat
-
SpringWebflux 方式实现,异步非阻塞 方式,基于 SpringWebflux+Reactor+Netty
两者使用的注解都是一样,区别是使用的组件不一样,示例程序如下:
引入webFlux依赖
|
|
service
|
|
controller
|
|
运行com.eh.webflux.WebfluxApplication#main
基于函数式实现WebFlux
说明
-
在使用函数式编程模型操作时候,需要自己初始化服务器
-
基于函数式编程模型时候,有两个核心接口:RouterFunction(实现路由功能,请求转发 给对应的 handler)和 HandlerFunction(处理请求生成响应的函数)。
1 2 3 4 5 6 7 8 9 10
@FunctionalInterface public interface RouterFunction<T extends ServerResponse> { /** * Return the {@linkplain HandlerFunction handler function} that matches the given request. * @param request the request to route * @return an {@code Mono} describing the {@code HandlerFunction} that matches this request, * or an empty {@code Mono} if there is no match */ Mono<HandlerFunction<T>> route(ServerRequest request);
1 2 3 4 5 6 7 8 9 10 11
@FunctionalInterface public interface HandlerFunction<T extends ServerResponse> { /** * Handle the given request. * @param request the request to handle * @return the response */ Mono<T> handle(ServerRequest request); }
-
核心任务定义两个函数 式接口的实现并且启动需要的服务器。
-
SpringWebflux 请 求 和 响 应 不 再 是 ServletRequest 和 ServletResponse , 而 是 ServerRequest 和 ServerResponse
演示步骤
-
创建Handler
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
package com.eh.webflux.function; import com.eh.webflux.entity.User; import com.eh.webflux.service.UserService; import org.springframework.http.MediaType; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.reactive.function.server.ServerResponse; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; public class UserHandler { private final UserService userService; public UserHandler(UserService userService) { this.userService = userService; } // 根据id查询 public Mono<ServerResponse> getUserById(ServerRequest request) { // 获取id值 int userId = Integer.parseInt(request.pathVariable("id")); // 调用service方法得到数据 Mono<User> userMono = userService.getUserById(userId); // 将userMono转换成Mono<ServerResponse> Mono<ServerResponse> notFound = ServerResponse.notFound().build(); // 练习reactor操作符,简洁写法参考getAllUsers() return userMono.flatMap(user -> ServerResponse.ok() // user -> Mono<ServerResponse>,所以使用flatMap .contentType(MediaType.APPLICATION_JSON) // json格式 .body(BodyInserters.fromValue(user))) // 写入body .switchIfEmpty(notFound); // 如果没找到使用空值返回 } // 查询所有 public Mono<ServerResponse> getAllUsers(ServerRequest request) { Flux<User> users = userService.getUsers(); return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(users, User.class); } // 添加 public Mono<ServerResponse> saveUser(ServerRequest request) { // 得到user对象 Mono<User> userMono = request.bodyToMono(User.class); return ServerResponse.ok().build(userService.saveUser(userMono)); } }
-
创建服务器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
package com.eh.webflux.function; import com.eh.webflux.service.UserService; import org.springframework.http.MediaType; import org.springframework.http.server.reactive.HttpHandler; import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; import org.springframework.web.reactive.function.server.RequestPredicates; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; import reactor.netty.http.server.HttpServer; import java.io.IOException; public class Server { // 创建路由 public RouterFunction<ServerResponse> routerFunction() { // 创建Handler UserHandler userHandler = new UserHandler(new UserService()); // 设置路由 return RouterFunctions.route( RequestPredicates.GET("/users/{id}") .and(RequestPredicates.accept(MediaType.APPLICATION_JSON)), userHandler::getUserById ).andRoute( RequestPredicates.GET("/users") .and(RequestPredicates.accept(MediaType.APPLICATION_JSON)) , userHandler::getAllUsers ); } // 创建服务器完成适配 public void createReactorServer() { // 创建HttpHandler HttpHandler httpHandler = RouterFunctions.toHttpHandler(routerFunction()); // 创建适配器 ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler); // 创建服务器 HttpServer httpServer = HttpServer.create(); // 绑定adapter并使用默认网络设置启动服务器,subscribe网络 httpServer.handle(adapter).bindNow(); } // 测试程序 public static void main(String[] args) throws IOException { Server server = new Server(); server.createReactorServer(); System.out.println("enter to exit"); System.in.read(); } }
-
测试
启动测试程序,控制台打印 端口号53142
1
20:46:05.206 [reactor-http-nio-1] DEBUG reactor.netty.tcp.TcpServer - [id: 0xe93dc51d, L:/0:0:0:0:0:0:0:0:53238] Bound new server
访问 http://localhost:53238/users
-
使用WebClient调用
此时服务器处于开启状态,还可以使用WebClient进行调用,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
package com.eh.webflux.function; import com.eh.webflux.entity.User; import org.springframework.http.MediaType; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Flux; public class Client { public static void main(String[] args) { // 创建客户端,传入baseUrl WebClient webClient = WebClient.create("http://localhost:53238"); // 根据id查询 Integer id = 1; User user = webClient.get().uri("/users/{id}", 1) .accept(MediaType.APPLICATION_JSON) .retrieve() // 发起请求并接受响应 .bodyToMono(User.class) .block(); System.out.println(user); // 查询所有员工 Flux<User> users = webClient.get().uri("/users") .accept(MediaType.APPLICATION_JSON) .retrieve() .bodyToFlux(User.class); users.buffer().doOnNext(System.out::println).blockFirst(); } }
输出:
1 2 3 4 5 6 7 8
20:56:33.531 [reactor-http-nio-1] DEBUG reactor.netty.resources.PooledConnectionProvider - [id: 0x43b6c05b, L:/127.0.0.1:53325 - R:localhost/127.0.0.1:53238] onStateChange(GET{uri=/users/1, connection=PooledConnection{channel=[id: 0x43b6c05b, L:/127.0.0.1:53325 - R:localhost/127.0.0.1:53238]}}, [request_sent]) 20:56:33.537 [reactor-http-nio-1] DEBUG reactor.netty.http.client.HttpClientOperations - [id: 0x43b6c05b, L:/127.0.0.1:53325 - R:localhost/127.0.0.1:53238] Received response (auto-read:false) : [Content-Type=application/json, Content-Length=26] 20:56:33.538 [reactor-http-nio-1] DEBUG reactor.netty.resources.PooledConnectionProvider - [id: 0x43b6c05b, L:/127.0.0.1:53325 - R:localhost/127.0.0.1:53238] onStateChange(GET{uri=/users/1, connection=PooledConnection{channel=[id: 0x43b6c05b, L:/127.0.0.1:53325 - R:localhost/127.0.0.1:53238]}}, [response_received]) 20:56:33.541 [reactor-http-nio-1] DEBUG org.springframework.web.reactive.function.client.ExchangeFunctions - [2053d869] Response 200 OK 20:56:33.652 [reactor-http-nio-1] DEBUG reactor.netty.channel.FluxReceive - [id: 0x43b6c05b, L:/127.0.0.1:53325 - R:localhost/127.0.0.1:53238] FluxReceive{pending=0, cancelled=false, inboundDone=false, inboundError=null}: subscribing inbound receiver 20:56:33.661 [reactor-http-nio-1] DEBUG reactor.netty.http.client.HttpClientOperations - [id: 0x43b6c05b, L:/127.0.0.1:53325 - R:localhost/127.0.0.1:53238] Received last HTTP packet 20:56:33.697 [reactor-http-nio-1] DEBUG org.springframework.http.codec.json.Jackson2JsonDecoder - [2053d869] Decoded [User(name=徐达, age=38)] User(name=徐达, age=38)
附: 完整示例地址