引子:被誉为“中国大数据第一人”的涂子沛先生在其成名做《数据之巅》里提到,摩尔定律、社交媒体、数据挖掘是大数据的三大成因。IBM的研究称,整我的类文明所得到的所有数据中,有90%是过去两年内产生的。在此背景下,包括NoSQL,Hadoop, Spark, Storm, Kylin在内的大批新技术应运而生。其中以RxJava和Reactor为表明的响应式(Reactive)编程技术针对的就是经典的大数据4V定义(Volume,Variety,Velocity,Value)中的Velocity,即高并发问题,而在即将发布的Spring 5中,也引入了响应式编程的支持。在接下来的几周,我会围绕响应式编程分三期与你分享个人一些学习心得。本篇是第三篇(下),经过一个简单的Spring 5示例应用,探一探即将于下月底发布的Spring 5的究竟。html
前情概要:java
【Spring 5】响应式Web框架前瞻react
响应式编程总览git
【Spring 5】响应式Web框架实战(上)github
上篇介绍了如何使用Spring MVC注解实现一个响应式Web应用(如下简称RP应用),本篇接着介绍另外一种实现方式——Router Functions。web
Router Functions是Spring 5新引入的一套Reactive风格(基于Flux和Mono)的函数式接口,主要包括RouterFunction
,HandlerFunction
和HandlerFilterFunction
,分别对应Spring MVC中的@RequestMapping
,@Controller
和HandlerInterceptor
(或者Servlet规范中的Filter
)。spring
和Router Functions搭配使用的是两个新的请求/响应模型,ServerRequest
和ServerResponse
,这两个模型一样提供了Reactive风格的接口。mongodb
下面接着看我GitHub上的示例工程里的例子。编程
@Configuration public class RestaurantServer implements CommandLineRunner { @Autowired private RestaurantHandler restaurantHandler; /** * 注册自定义RouterFunction */ @Bean public RouterFunction<ServerResponse> restaurantRouter() { RouterFunction<ServerResponse> router = route(GET("/reactive/restaurants").and(accept(APPLICATION_JSON_UTF8)), restaurantHandler::findAll) .andRoute(GET("/reactive/delay/restaurants").and(accept(APPLICATION_JSON_UTF8)), restaurantHandler::findAllDelay) .andRoute(GET("/reactive/restaurants/{id}").and(accept(APPLICATION_JSON_UTF8)), restaurantHandler::get) .andRoute(POST("/reactive/restaurants").and(accept(APPLICATION_JSON_UTF8)).and(contentType(APPLICATION_JSON_UTF8)), restaurantHandler::create) .andRoute(DELETE("/reactive/restaurants/{id}").and(accept(APPLICATION_JSON_UTF8)), restaurantHandler::delete) // 注册自定义HandlerFilterFunction .filter((request, next) -> { if (HttpMethod.PUT.equals(request.method())) { return ServerResponse.status(HttpStatus.BAD_REQUEST).build(); } return next.handle(request); }); return router; } @Override public void run(String... args) throws Exception { RouterFunction<ServerResponse> router = restaurantRouter(); // 转化为通用的Reactive HttpHandler HttpHandler httpHandler = toHttpHandler(router); // 适配成Netty Server所需的Handler ReactorHttpHandlerAdapter httpAdapter = new ReactorHttpHandlerAdapter(httpHandler); // 建立Netty Server HttpServer server = HttpServer.create("localhost", 9090); // 注册Handler并启动Netty Server server.newHandler(httpAdapter).block(); } }
能够看到,使用Router Functions实现RP应用时,你须要本身建立和管理容器,也就是说Spring 5并无针对Router Functions提供IoC支持,这是Router Functions和Spring MVC相比最大的不一样。除此以外,你须要经过RouterFunction
的API(而不是注解)来配置路由表和过滤器。对于简单的应用,这样作问题不大,但对于上规模的应用,就会致使两个问题:1)Router的定义愈来愈庞大;2)因为URI和Handler分开定义,路由表的维护成本愈来愈高。那为何Spring 5会选择这种方式定义Router呢?接着往下看。并发
@Component public class RestaurantHandler { /** * 扩展ReactiveCrudRepository接口,提供基本的CRUD操做 */ private final RestaurantRepository restaurantRepository; /** * spring-boot-starter-data-mongodb-reactive提供的通用模板 */ private final ReactiveMongoTemplate reactiveMongoTemplate; public RestaurantHandler(RestaurantRepository restaurantRepository, ReactiveMongoTemplate reactiveMongoTemplate) { this.restaurantRepository = restaurantRepository; this.reactiveMongoTemplate = reactiveMongoTemplate; } public Mono<ServerResponse> findAll(ServerRequest request) { Flux<Restaurant> result = restaurantRepository.findAll(); return ok().contentType(APPLICATION_JSON_UTF8).body(result, Restaurant.class); } public Mono<ServerResponse> findAllDelay(ServerRequest request) { Flux<Restaurant> result = restaurantRepository.findAll().delayElements(Duration.ofSeconds(1)); return ok().contentType(APPLICATION_JSON_UTF8).body(result, Restaurant.class); } public Mono<ServerResponse> get(ServerRequest request) { String id = request.pathVariable("id"); Mono<Restaurant> result = restaurantRepository.findById(id); return ok().contentType(APPLICATION_JSON_UTF8).body(result, Restaurant.class); } public Mono<ServerResponse> create(ServerRequest request) { Flux<Restaurant> restaurants = request.bodyToFlux(Restaurant.class); Flux<Restaurant> result = restaurants .buffer(10000) .flatMap(rs -> reactiveMongoTemplate.insert(rs, Restaurant.class)); return ok().contentType(APPLICATION_JSON_UTF8).body(result, Restaurant.class); } public Mono<ServerResponse> delete(ServerRequest request) { String id = request.pathVariable("id"); Mono<Void> result = restaurantRepository.deleteById(id); return ok().contentType(APPLICATION_JSON_UTF8).build(result); } }
对比上篇的RestaurantController
,因为去除了路由信息,RestaurantHandler
变得很是函数化,能够说就是一组相关的HandlerFunction
的集合,同时各个方法的可复用性也大为提高。这就回答了上一小节提出的疑问,即以牺牲可维护性为代价,换取更好的函数特性。
@RunWith(SpringRunner.class) @SpringBootTest public class RestaurantHandlerTests extends BaseUnitTests { @Autowired private RouterFunction<ServerResponse> restaurantRouter; @Override protected WebTestClient prepareClient() { WebTestClient webClient = WebTestClient.bindToRouterFunction(restaurantRouter) .configureClient().baseUrl("http://localhost:9090").responseTimeout(Duration.ofMinutes(1)).build(); return webClient; } }
和针对Controller的单元测试相比,编写Handler的单元测试的主要区别在于初始化WebTestClient
方式的不一样,测试方法的主体能够彻底复用。
到此,有关响应式编程的介绍就暂且告一段落。回顾这四篇文章,我先是从响应式宣言提及,而后介绍了响应式编程的基本概念和关键特性,而且详解了Spring 5中和响应式编程相关的新特性,最后以一个示例应用结尾。但愿读完这些文章,对你理解响应式编程能有所帮助。欢迎你到个人留言板分享,和你们一块儿过过招。