一, 快速搭建webflux项目
1, 引入相关依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<!-- 解决mac系统Unable to load io.netty.resolver.dns.macos.MacOSDnsServerAddressStreamProvider异常 -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.72.Final</version>
</dependency>
启动类还是原来的@SpringBootApplication.
如果想要跳转指定静态页面,需要注入RouterFunction
@Value("classpath:pages/index.html")
private Resource indexHtml;
@Bean
public RouterFunction<ServerResponse> route(){
return RouterFunctions
.route(RequestPredicates.GET("/"),request -> pageRespons(indexHtml))
.andRoute(RequestPredicates.GET("/flux"),request -> fluxRespons());
}
private Mono<ServerResponse> fluxRespons() {
Stream<Integer> randomStream = new Random().ints().map(i -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return i;
}).boxed();
Flux<Integer> flux = Flux.fromStream(randomStream);
return ServerResponse.ok().contentType(MediaType.TEXT_EVENT_STREAM).body(flux,Integer.class);
}
private Mono<ServerResponse> pageRespons(Resource indexHtml) {
return ServerResponse.ok().contentType(MediaType.TEXT_HTML).body(DataBufferUtils.read(indexHtml,new DefaultDataBufferFactory(),4096),DataBuffer.class);
}
在resources目录下创建pages目录,pages下创建index.html
<html>
<head></head>
<body>
home
</body>
</html>
二, 相关API使用说明
1, webflux返回值一般有Mono或Flux包装
2, webflux是懒加载,不能像传统那样写逻辑,需要return Mono或return Flux并且一个方法里只能return一个,其他逻辑需要在这个逻辑里面return;如果存在多个并行的逻辑,可以通过zip或zipWith来进行连接
3, zip与zipwith用法:
zip连接多个Mono,并且每个Mono的返回值要一致;
zipWith连接一个Mono,多个zipwith嵌套使用允许不同的返回值.
4, mono里的doOnSuccess/doOnXX是在zip、zipwith执行完后才会执行
5, subscribe也是在zip、zipwith执行完后才会执行
6, Mono的mapNotNull/switchIfEmpty是在该Mono执行完后执行,按照Mono返回的对象互斥执行
7, Mono.defer()与Flux.defer()区别在于:前者返回Mono对象,后者返回Flux对象集合.
8, Mono> 转Flux与Flux转Mono>
Flux.collectList()->转Mono>Mono>.flatMapMany(Flux::fromIterable)转Flux