Reactive Springspringcloud学习,微服务

Reactive Spring -- 2. Spring We

2019-02-22  本文已影响8人  ted005

工程地址分支为reactive-stack

Web层的Reactive:Spring WebFlux

Spring WebFlux是异步的非阻塞的

传统的Spring MVC基于Servlet,是阻塞式的,每次请求由一个线程处理;而Spring WebFlux通过事件循环Event Loop的方式,由单个线程非阻塞的处理事件。当需要处理耗时任务时,Event Loop绑定的线程会新启线程来执行,完成后通知Event Loop

与Spring MVC的关系
Spring WebFlux
使用Spring WebFlux
  1. 引入依赖

spring-boot-starter-webflux内置的服务器是Netty,而不是Tomcat。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
  1. 全流程Reactive技术栈

从Controller到Service、Repository层,都采用Reactive模式。每一层的数据都返回FluxMono类型,框架会自动调用subscribe方法,以使数据流动。

全流程Reactive

Repository层的Reactive

目前支持Reactive模式的数据存储只有Redis,MongoDB等,传统的关系型数据库和相应的JDBC驱动还不支持。

但是可以将Repository返回的模型或集合转换为Reactive类型:

List<Person> personList = personRepository.findAll();
Flux<Person> personFlux = Flux.fromIterable(personList);

也可以将Flux或Mono中的数据元素提取出来,即转换为传统模型:

Iterable<Person> personIterable = personFlux.toIterable();

Person person = personMono.block();

注意:toIterable(), block()等提取数据的方式都是阻塞的。

当然,要实现全流程的Reactive模式,需要MongoDB等文档数据库。

上述的类型转换是在已有传统关系型数据库,无法换库时采用的方案,即在Repository层仍然是非Reactive模式的,在Service层将模型或集合转换为Reactive类型,这样在Controller层可以使用。

上一篇 下一篇

猜你喜欢

热点阅读