Spring-Webflux + Reactor + Netty 初体验

安装

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

接口

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.stream.Stream;

/**
 * 功能描述
 *
 * @author jason
 */
@RestController
@RequestMapping("/test")
public class TestController {
    
    

    /**
     * http://127.0.0.1:8081/test/hello
     */
    @GetMapping("/hello")
    public String hello() {
    
    
        long start = System.currentTimeMillis();
        String helloStr = getHelloStr();
        System.out.println("普通接口耗时:" + (System.currentTimeMillis() - start));
        return helloStr;
    }

    /**
     * http://127.0.0.1:8081/test/helloWebMono
     */
    @GetMapping("/helloWebMono")
    public Mono<String> hello0() {
    
    
        long start = System.currentTimeMillis();
        Mono<String> hello0 = Mono.fromSupplier(this::getHelloStr);
        System.out.println("WebFlux 接口耗时:" + (System.currentTimeMillis() - start));
//        hello0.subscribe(result -> System.out.println("回调结果:" + result));
        return hello0;
    }

    /**
     * http://127.0.0.1:8081/test/helloWebFlux
     */
    @GetMapping("/helloWebFlux")
    public Flux<String> hello1() {
    
    
        long start = System.currentTimeMillis();
        Flux<String> hello0 = Flux.fromStream(this::getHelloList);
        System.out.println("WebFlux 接口耗时:" + (System.currentTimeMillis() - start));
//        hello0.subscribe(result -> System.out.println("回调结果:" + result));
        return hello0;
    }

    /**
     * http://127.0.0.1:8081/test/stream
     */
    @GetMapping("/stream")
    public Flux<String> stream() {
    
    
        Flux<String> fromStream = Flux.fromStream(this::getHelloList);
        return fromStream.log();
    }

    private String getHelloStr() {
    
    
        try {
    
    
            Thread.sleep(2000);
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        return "hello";
    }

    private Stream<String> getHelloList() {
    
    
        try {
    
    
            Thread.sleep(2000);
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        return Stream.of("Hello", "Spring", "Webflux");
    }

}

控制台

对于前端来说,响应速度是一致的,但系统的吞吐量提高了

Netty started on port 8081 (http)

普通接口耗时:2003
WebFlux 接口耗时:0

源码

https://gitee.com/zhaomingjian/workspace_jason_demo/tree/master/spring-boot-webflux