Spring WebFlux


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 依赖:


    org.springframework.boot
    spring-boot-starter-webflux

写个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 hello2() {
        long start = System.currentTimeMillis();
        Mono 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 可以仔细阅读官方文档:

官方文档:https://docs.spring.io/spring-framework/docs/5.0.0.RELEASE/spring-framework-reference/web-reactive.html#webflux-introduction

参考文章:

江南一点雨 webflex 系列文章
WebFlux简介