一, 快速搭建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

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐