异步编程实战之webflux

本文介绍了如何在SpringBoot2.6.5中快速搭建WebFlux项目,包括引入相关依赖、处理MacOS异常,以及如何定义路由和使用Flux/MonoAPI。重点讲解了WebFlux的返回值类型、懒加载特性及操作符如zip和zipWith的用法。
摘要由CSDN通过智能技术生成

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱编程的Loren

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值