Spring WebFlux
一、什么是webFlux
首先來看看Spring 官網上的一張對比圖:
通過這張圖我們可以知道 Spring WebFlux 對應的是 Spring MVC:
Spring WebFlux | Spring MVC |
---|---|
基於 Reactive 技術棧 | 基於 Servlet 技術棧 |
Spring WebFlux 是一個非阻塞的web框架,它完全利用了多核下一代處理器的優勢,可以處理大量的並發連接 | Spring MVC 構建在Servlet API之上,並使用同步阻塞I/O架構和每個線程一個請求的模型 |
WebFlux 需要使用 Netty 容器和支持 Servlet3.1+ 的容器(底層默認使用的是Netty 容器) | Spring MVC 使用支持 Servlet 的容器 |
只支持反應式的數據存儲(響應式的異步非阻塞驅動程序)Mongo, Cassandra, Redis, Couchbase | JDBC、JPA、NoSQL |
總結下:
Spring WebFlux 是一個異步非阻塞式 IO 模型,通過少量的容器線程就可以支撐大量的並發訪問,所以 Spring WebFlux 可以有效提升系統的吞吐量和伸縮性,特別是在一些 IO 密集型應用中,Spring WebFlux 的優勢明顯。例如微服務網關 Spring Cloud Gateway 就使用了 WebFlux,這樣可以有效提升網管對下游服務的吞吐量。
不過需要注意的是,接口的響應時間並不會因為使用了 WebFlux 而縮短,服務端的處理結果還是得由 worker 線程處理完成之后再返回給前端。
WebFlux 支持Servlet3.1+ 容器,如 Tomcat、Jetty,或者是非 Servlet 容器,如 Netty 和 Undertow。底層默認使用 Netty 容器。
二、WebFlux 體驗一下
創建一個 springboot 工程,引入 WebFlux 依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
寫個controller :
@RestController
public class TestController {
@GetMapping("/hello")
public String hello() {
long start = System.currentTimeMillis();
String helloStr = getHelloStr();
System.out.println("普通接口耗時:" + (System.currentTimeMillis() - start));
return helloStr;
}
@GetMapping("/hello2")
public Mono<String> hello2() {
long start = System.currentTimeMillis();
Mono<String> hello2 = Mono.fromSupplier(() -> getHelloStr());
System.out.println("WebFlux 接口耗時:" + (System.currentTimeMillis() - start));
return hello2;
}
private String getHelloStr() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "hello";
}
}
啟動項目:
從啟動日志中可以看到 webFlux 默認使用 Netty 容器。
測試接口:
可以看出 spring webFlux 與 spring MVC 差異。
什么是 Reactor
Spring Reactor 是 Pivotal 團隊基於反應式編程實現的一種方案,這是一種非阻塞,並且由事件驅動的編程方案,它使用函數式編程實現。
Reactor 還提供了異步序列 API Flux(用於 N 個元素)和 Mono(用於 0|1 個元素),並完全遵循和實現了“響應式擴展規范”(Reactive Extensions Specification)。
上文示例中的 webFlux 接口返回值 就是使用 Mono。
- Mono:返回 0 或 1 個元素。
- Flux:返回 N 個元素。
這里沒做過過多的講解,想要更詳細的了解 webFlux 可以仔細閱讀官方文檔:
參考文章:
江南一點雨 webflex 系列文章
WebFlux簡介
Spring Boot 2.0 WebFlux 教程 (一) | 入門篇