spring webflux是spirng 5 引入的能构建异步响应式服务的新特性。
异步响应式web容器底层实现可选择netty,undertow,servlet 3.1+容器。
和传统的阻塞式servlet容器不一样。响应式容器能进一步提高资源的利用率,避免线程长时间处于等待状态,能以较少的线程处理更多的请求,缺点是整个处理链路必须是异步的,是基于事件响应的,不能阻塞事件线程,不然服务器性能会急剧下降,当然spring webflux并不能完整的替代传统的阻塞式容器,可根据需求进行选型。
2.spring-webflux的使用
引入maven依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.7.2version>
<relativePath/>
parent>
<groupId>com.lygroupId>
<artifactId>spring-webflux-sessionartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>spring-webflux-sessionname>
<description>Demo project for Spring Bootdescription>
<properties>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webfluxartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-configuration-processorartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-redisartifactId>
dependency>
<dependency>
<groupId>io.projectreactorgroupId>
<artifactId>reactor-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframework.sessiongroupId>
<artifactId>spring-session-data-redisartifactId>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
exclude>
excludes>
configuration>
plugin>
plugins>
build>
project>
可在拥有Configruation注解类上添加enablewebflux注解,并实现WebFluxConfigurer接口,用于添加定制的codec,handMapping,cors设置等能力
@SpringBootApplication
@EnableRedisWebSession
@EnableWebFlux
public class SpringWebfluxSessionApplication implements WebFluxConfigurer {
public static void main(String[] args) {
SpringApplication.run(SpringWebfluxSessionApplication.class, args);
}
}
webflux兼容大部分springmvc的注解
我们可以像mvc那样创建controller处理我们的请求。
package com.ly;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.server.WebSession;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@RestController
public class DemoController {
@Autowired
private GoodService goodService;
@GetMapping("/good/{id}")
public Mono<Good> getGoodById(@PathVariable int id, WebSession session){
if(session.getAttribute("name") == null){
session.getAttributes().put("name","liuyu");
}
return goodService.getGoodById(id);
}
@GetMapping("/goods")
public Flux<Good> getGoods(){
return goodService.getGoods();
}
@GetMapping("/hello")
public Mono<String> hello(){
WebClient client = WebClient.create();
Map<String,Object> map = new HashMap<>();
map.put("name","liuyu");
return client.post().uri("http://localhost:8088/hello1").contentType(MediaType.APPLICATION_JSON)
.bodyValue(map).retrieve()
.bodyToMono(String.class);
}
}
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
class Good{
private int id;
private String goodName;
private int stock;
}
interface GoodService{
Mono<Good> getGoodById(int id);
Flux<Good> getGoods();
Mono<Void> addGood(Good good);
}
@Service
class GoodServiceImpl implements GoodService{
private static Map<Integer,Good> goodMap = new ConcurrentHashMap<>();
static {
goodMap.put(1, Good.builder().id(1).goodName("纸巾").stock(100).build());
goodMap.put(2, Good.builder().id(2).goodName("洗衣液").stock(100).build());
goodMap.put(3, Good.builder().id(3).goodName("洗发水").stock(100).build());
}
@Override
public Mono<Good> getGoodById(int id) {
return Mono.justOrEmpty(goodMap.get(id));
}
@Override
public Flux<Good> getGoods() {
return Flux.fromIterable(goodMap.values());
}
@Override
public Mono<Void> addGood(Good good) {
return null;
}
}
Mono和Flux是spring webflux用来处理响应式工作流的核心api,
Mono表示0或1个元素,
Flux表示0至N和元素,
他们本身都具备成功或异常2种状态,且都实现了pulish接口,
成功或异常时都会通知相关的订阅者。
具体的api介绍请参考官方文档。
https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux-new-framework
https://projectreactor.io/docs/core/release/reference/index.html#core-features