以spring官方文档为基础,官方地址:Spring Boot_Web
Spring Boot非常适合web应用程序的开发。可以使用嵌入的Tomcat、Jetty、Undertow或Netty创建一个自包含的HTTP服务器。大多数web应用程序使用spring-boot-starter-web模块来快速启动和运行。也可以选择使用spring-boot-starter-webflux模块来构建响应式web应用程序。
Spring Boot通过为Spring Webflux提供自动配置,简化了响应式web应用程序的开发。
1. 关于Spring WebFlux Framework
Spring WebFlux是Spring framework 5.0中引入的一个新的响应式web框架。与Spring MVC不同,它不需要servlet API,是完全异步和非阻塞的,并通过Reactor项目实现了Reactive Streams规范。
Spring WebFlux有两种类型:功能性和基于注解的。基于注解的模型非常接近Spring MVC模型,如下面的例子所示:
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/users")
public class MyRestController {
private final UserRepository userRepository;
private final CustomerRepository customerRepository;
public MyRestController(UserRepository userRepository, CustomerRepository customerRepository) {
this.userRepository = userRepository;
this.customerRepository = customerRepository;
}
@GetMapping("/{user}")
public Mono<User> getUser(@PathVariable Long userId) {
return this.userRepository.findById(userId);
}
@GetMapping("/{user}/customers")
public Flux<Customer> getUserCustomers(@PathVariable Long userId) {
return this.userRepository.findById