实战SpringCloud响应式微服务系列教程(第九章)使用Spring WebFlux构建响应式RESTful服务
本文为实战SpringCloud响应式微服务系列教程第九章,讲解使用Spring WebFlux构建响应式RESTful服务。建议没有之前基础的童鞋,先看之前的章节,章节目录放在文末。
从本节开始我们将正式进入构建响应式服务的世界。在Spring boot的基础上,我们将引入全新的Spring WebFlux框架。
WebFlux名称中的Flux来源于上章节介绍的来自Reactor框架中的Flux组件。该框架中包含了对响应式HTTP、服务器推送事件以及Websocket的客户端和服务端的支持。
在构架响应式服务上,WebFlux支持两种不同的编程模型:
- 第一种是与SpringMvc中同样使用的基于java注解的方式;
- 第二种是基于java8中提供的lambda表达式的函数式编程模型。
1.1使用 Spring Initializer初始化响应式web应用
创建WebFlux应用最简单的方式便是使用Spring boot提供的Spring Initializer初始化模板。
直接访问Spring Initializer网站(http://start.spring.io),选择创建一个maven或者Gradle项目并制定相应的Group和Artifact,然后在添加依赖中选择maven进行代码依赖管理。
打开所下载项目中的pom文件,会找到如下依赖。
- spring-boot-starter-webflux构成响应式web程序开发的基础;
- spring-boot-starter-test是包含JUnit、Spring boot Test、Mockito、AssertJ、JSONAssert以及Hamcerst等工具在内的测试组件库;
- reactor-test则是用来测试Reactor框架的测试组件;
- spring-boot-starter-data-mongodb-reactive和spring-boot-starter-data-redis-reactive则是响应式数据访问组件。
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> <!--Lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> <version>1.16.22</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb-reactive</artifactId> </dependency> <!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis-reactive</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.projectreactor</groupId> <