webflux:
反应式编程reactor的产物,采用发布订阅模式,引入netty的nio,比较适合IO密集型应用。
因普遍应用使用的DB链接是IO阻塞型,因此在一般应用中无法体现它的优势。redis和mongoDB支持reactor。
前言: Flux && Mono
Flux: 可返回1到n个结果,
Mono: 仅返回0到1个结果
MAVEN 依赖:
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<version>2.1.9.RELEASE</version>
</dependency>
注意: spring-boot-starter-webflux 和 spring-boot-starter-webmvc 会冲突,因此如果有webmvc请排除掉。
启动引入
@SpringBootApplication
@EnableWebFlux
public class TestWebfluxApp {
SpringApplication.run(TestWebfluxApp.class, args);
}
controller方式使用
@Slf4j
@RequestMapping("/webflux")
@RestController
public class TestWebFluxController {
/**
* Mono
* @param user
* @return
*/
@RequestMapping("/user/new")
public Mono<String> user(@RequestBody User user){
System.out.println("user:" +user);
WebClient webClient = WebClient.create("http://127.0.0.1:8089");
Mono<ClientResponse> exchange = webClient.get().uri("/algo/yumc/get?test=junitTest1234&sk={0}", "123456").exchange();
System.out.println("user2: ---------------------");
Mono<String> mono = Mono.just("1234567");
return exchange.block(Duration.ofSeconds(1)).bodyToMono(String.class);
}
/**
* Flux
* @return
*/
@RequestMapping("/user/list")
public Flux<String> user(){
WebClient webClient = WebClient.create("http://127.0.0.1:8089");
Mono<ClientResponse> exchange = webClient.get().uri("/algo/yumc/get?test=junitTest1234&sk={0}", "123456").exchange();
System.out.println("user2: ---------------------");
Flux<String> stringFlux = Flux.just("1234","5678");
return exchange.block(Duration.ofSeconds(1)).bodyToFlux(String.class);
}
endpoint方式使用
@Configuration
public class WebfluxConfiguration {
@Autowired
private UserHandler userHandler;
@Bean
@Qualifier("userRouter")
public RouterFunction<ServerResponse> userRouter(){
return RouterFunctions.nest(RequestPredicates.path("/flux/user"),
RouterFunctions.route(RequestPredicates.GET("/info"), UserHandler::getUserInfo)
.andRoute(RequestPredicates.GET("/list"), UserHandler::getUserList));
}
@Component
public class UserHandler {
/**
* request
* @param serverRequest
* @return
*/
public static Mono<ServerResponse> getUserInfo(ServerRequest serverRequest) {
User user = new User();
user.setId(12345);
user.setName("张三");
return ServerResponse.ok()
.contentType(MediaType.TEXT_PLAIN)
.body(BodyInserters.fromObject(user));
}
常见异常:
-
org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'text/xml;charset=UTF-8' not supported for bodyType
原因:MediaType.TEXT_PLAIN 转变为 MediaType.APPLICATION_JSON 即可