WebFlux初体验
背景
初体验
依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency>
HelloWorld
@GetMapping("ping") public Mono<String> ping() { return Mono.just("pong"); }
自定义响应码
@GetMapping("/health") public Mono<ResponseEntity<String>> health() { if (online) { return Mono.just("ok").map(m -> new ResponseEntity<>(m, HttpStatus.OK)); } else { return Mono.just("offline").map(m -> new ResponseEntity<>(m, HttpStatus.INTERNAL_SERVER_ERROR)); } }
性能比较Tomcat VS Webflux
Tomcat
Server Software: Server Hostname: localhost Server Port: 8081 Document Path: /health Document Length: 2 bytes Concurrency Level: 100 Time taken for tests: 18.029 seconds Complete requests: 100000 Failed requests: 0 Keep-Alive requests: 99046 Total transferred: 16772334 bytes HTML transferred: 200000 bytes Requests per second: 5546.51 [#/sec] (mean) Time per request: 18.029 [ms] (mean) Time per request: 0.180 [ms] (mean, across all concurrent requests) Transfer rate: 908.48 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 0 0 2.1 0 113 Processing: 1 18 10.7 16 129 Waiting: 0 18 10.6 16 117 Total: 1 18 11.1 16 142 Percentage of the requests served within a certain time (ms) 50% 16 66% 19 75% 22 80% 24 90% 30 95% 37 98% 49 99% 59 100% 142 (longest request)
建联 最慢时有 113ms。