1.Spring flux简介
Spring WebFlux是Spring Framework 5.0中引入的新的反应式Web框架。 与Spring MVC不同,它不需要Servlet API,完全异步和非阻塞, 并通过Reactor项目实现Reactive Streams规范。 并且可以在诸如Netty,Undertow和Servlet 3.1+容器的服务器上运行
Spring WebFlux internally uses Project Reactor and its publisher implementations – Flux and Mono.
Flux接口:https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html
Mono接口:https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html
2. 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
3.Reactive RestController 的一个例子
@RestController
@RequestMapping("/employees")
public class EmployeeController {
private final EmployeeRepository employeeRepository;
// constructor...
}
3.1 单一结果
我们封装了单一结果的资源到Mono对象里面
@GetMapping("/{id}")
private Mono<Employee> getEmployeeById(@PathVariable String id) {
return employeeRepository.findEmployeeById(id);
}
3.2 集合结果
@GetMapping
private Flux<Employee> getAllEmployees() {
return employeeRepository.findAllEmployees();
}
3.3 Reactive Web Client
public class EmployeeWebClient {
WebClient client = WebClient.create("http://localhost:8080");
Mono<Employee> employeeMono = client.get()
.uri("/employees/{id}", "1")
.retrieve()
.bodyToMono(Employee.class);
employeeMono.subscribe(System.out::println);
}
Flux<Employee> employeeFlux = client.get()
.uri("/employees")
.retrieve()
.bodyToFlux(Employee.class);
employeeFlux.subscribe(System.out::println);
4. 总结
通过上面的例子基本上了解如何用webFlux 做了一个简单的demo,基本能了解和 Flux 和 Mono接口的区别。后续还需要研究 flux接口具体的实现细节。