什么是webflux
- Spingboot 5.0之后出现的
- 继续Reactive Streams API 实现的
-
为什么有webFlux
对于非阻塞 Web 应用需要
- 并发量大的时候降低资源的开销,提升性能
- 使用极少数的线程和较少的内存就能并发支持
- 必须使用非阻塞的web服务器
- netty (默认)
- jetty
- war运行可能会出问题,没测试过
- 并发量大的时候降低资源的开销,提升性能
- 函数式编程
使用建议
- 原有的Spring Mvc 应用正常运行就别换成webflux
- 依赖了大量的阻塞式持久化API和网络API,建议使用 MVC
- mysql数据库
- 已经使用了非阻塞技术栈,可以考虑使用WebFlux
- redis
- mongodb
- 想要使用Java8 Lambda 结合轻量级函数式框架,可以考虑WebFlux
WebFlux两中编程模型
- 基于注解的控制器
- 常用注解
- @Controller
- @RequestMapping 及其等价注解
- @RequestBody / @ResponseBody
- 返回值
- Mono
- 0或者1个返回
- Flux
- 多个返回
- Mono
- 常用注解
- 函数式Endpoints
栗子例子
/*** @link https://www.jianshu.com/p/1f610b90d40c* @return*/@GetMapping("mono")public Mono<ResultVO<List<String>>> mono() {// Mono.just()方法会发射一个元素return Mono.just(ResultVO.successForData(Arrays.asList("hello", "webflux", "spring", "boot")));}/*** @link https://www.jianshu.com/p/1f610b90d40c* @return*/@GetMapping("flux")public Flux<ResultVO<List<String>>> flux() {// Mono 最多发射一个数据,Flux 可以发射多个数据return Flux.just(ResultVO.successForData(Arrays.asList("hello", "webflux", "spring", "boot")),ResultVO.successForData(Arrays.asList("hello1", "webflux1", "spring1", "boot1")),ResultVO.successForData(Arrays.asList("hello2", "webflux2", "spring2", "boot2")));}GET http://localhost:8080/api/flux[{"code": 200,"message": "success","data": ["hello","webflux","spring","boot"],"ts": 1614045969727,"success": true},{"code": 200,"message": "success","data": ["hello1","webflux1","spring1","boot1"],"ts": 1614045969729,"success": true},{"code": 200,"message": "success","data": ["hello2","webflux2","spring2","boot2"],"ts": 1614045969729,"success": true}]
