Spring在2017年下半年迎来了Webflux,Springboot 2.x也对其进行了支持,官方提供了各种响应式编程的starter,Webflux的出现填补了Spring在响应式编程上的空白,关于响应式编程与传统的Servlet编程到底谁优谁劣,网上很多大神已经做过测试,两者也各有所长,由于刚接触Webflux,学习的最佳途径就是实践,所以我先从环境搭建开始,再实现简单的CRUD功能,在此记录一下自己的学习过程,方便以后温故。
第一步肯定是创建工程,引入基础依赖,springboot 官方有提供webflux的starter直接引入即可
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
dao层也有对应的reactive JPA,此处我还是使用非reactive的,后续有时间再尝试切换;创建数据库表,建立对应的实体类
@Data
@Entity
@Table(name = "tbl_customer")
public class CustomerDomain implements Serializable {
private static final long serialVersionUID = 2679712462712078985L;
@Id
@GeneratedValue(generator = "user-uuid")
@GenericGenerator(strategy = "uuid",name = "user-uuid")
private String id;
private String name;
private String gender;
private Integer age;
private String phone;
private String address;
}
编写的Handler,Flux<T>用于接收多个返回实例,Mono<T>用于接收单个实例
@Component
public class CustomerHandler {
@Autowired
private CustomerService service;
public Mono<ServerResponse> findAll(ServerRequest request){
Flux<CustomerDomain> domainFlux = service.findAll();
return ServerResponse.ok().body(domainFlux, List.class);
}
public Mono<ServerResponse> findOne(ServerRequest request){
Mono<CustomerDomain> domainMono = service.findOne(request.pathVariable("userId"));
return ServerResponse.ok().body(domainMono,CustomerDomain.class);
}
}
核心路由Router
@Configuration
public class CustomerRouter {
@Bean
@Autowired
public RouterFunction<ServerResponse> routerFunction(CustomerHandler handler){
return route(GET("/query/{userId}").and(accept(MediaType.APPLICATION_JSON)),handler::findOne)
.and(route(GET("/list/all").and(accept(MediaType.APPLICATION_JSON)),handler::findAll));
}
}
service逻辑处理
@Service
public class CustomerService {
@Autowired
private CustomerRepository repository;
public Mono<CustomerDomain> save(CustomerDomain customer){
return Mono.just(repository.save(customer));
}
public Mono<CustomerDomain> findOne(String id){
return Mono.just(repository.findById(id).get());
}
public Flux<CustomerDomain> findAll(){
return Flux.fromStream(repository.findAll().stream());
}
}
有了router之后,可以不用像springmvc一样再定义Controller,只需在router中定义好请求方式,访问的url,后续直接请求即可。