大纲
Spring Boot 2.X - WebFlux 响应式编程学习(二)
Spring Boot 2 WebFlux 之
Router Functions
方式实现,文中Spring Boot
版本为2.1.3.RELEASE
1. 创建SpringBoot项目:
通过Spring Initializr
工具创建一个SpringBoot项目,引入以下相关依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
2. 编写配置
application.yml
:
spring:
data:
mongodb:
uri: mongodb://localhost/webflux
注:Mongo 和 Spring Boot 配置中的默认端口均是27017
,这里可以不配。
3. 修改主启动类
在主运行程序上加注解@EnableReactiveMongoRepositories
启用响应式Mongo仓库功能
@SpringBootApplication
@EnableReactiveMongoRepositories
public class SpringBootV2WebfluxRouterFunctionApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootV2WebfluxRouterFunctionApplication.class, args);
}
}
4. 编写Bean
创建一个User实体:
User.java
@Document(collection = "user")
@Data
@Accessors