WebFlux快速上手

WebFlux快速上手,第1张

WebFlux快速上手

一、新建项目

示例使用IDEA快速创建基于SpringBoot的工程。




springboot 2.3.1

java 8

WebFlux 必须选用Reactive的库

POM 依赖

        <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

二、Controller

WebFlux 的Controller 可以沿用SpringMVC 的方式,但是返回结果需要使用Mono或者Flux。




创建一个接口,返回http状态


import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono; /**
* test
*
* @author opal
* @since 2020-07-17 10:04
*/
@RestController
@RequestMapping("/test")
public class TestController { volatile int count502 = 0;
volatile int count200 = 0;
/**
* 返回502状态
* @author opal
* @since 2020-07-17 10:04
*/
@GetMapping("/status502")
public Mono<String> status502(ServerWebExchange exchange){
count502++;
String msg = "这是502页面,第"+ count502 +"次访问";
exchange.getResponse().setStatusCode(HttpStatus.BAD_GATEWAY);
System.out.println(msg);
return Mono.just(msg);
} /**
* 返回200状态
* @author opal
* @since 2020-07-17 10:04
*/
@GetMapping("/status200")
public Flux<String> status200(){
count200++;
String msg = "这是200页面,第"+ count200 +"次访问";
System.out.println(msg);
return Flux.just("这是200页面", ", 第"+ count200 +"次访问");
}
}

跑起来测试一下:

结语

WebFlux 应用中,所有数据都应该以Mono、Flux的形式表示,这样才能带来最好的性能和高吞吐量,Mono和Flux 这两种数据模型是WebFlux的核心。




WebFulx要学好,需要掌握Reactor(Mono、Flux), 这跟stream很像,建议学习一下stream。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/585740.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-12
下一篇 2022-04-12

发表评论

登录后才能评论

评论列表(0条)

保存