這一篇文章介紹SpringBoot使用WebFlux響應式編程操做MongoDb數據庫。html
在以前一篇簡單介紹了WebFlux響應式編程的操做,咱們在來看一下下圖,能夠看到,在目前的Spring WebFlux尚未支持相似Mysql這樣的關係型數據庫,因此本文以MongoDb數據庫爲例。java
接下來介紹SpringBoot使用WebFlux響應式編程操做MongoDb數據庫。react
新建項目,在項目中加入webflux依賴和mongodb-reactive依賴,完整pom代碼以下:git
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dalaoyang</groupId>
<artifactId>springboot_mongodb2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot_mongodb2</name>
<description>springboot_mongodb2</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<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.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
複製代碼
配置文件中配置mongodb數據庫信息,以前文章有介紹,這裏就不介紹了,配置文件代碼以下:web
##端口號
server.port=8888
##mongo配置
spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.database=test
複製代碼
啓動類是默認生成的,沒有作任何修改,代碼以下:spring
package com.dalaoyang;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootMongodb2Application {
public static void main(String[] args) {
SpringApplication.run(SpringbootMongodb2Application.class, args);
}
}
複製代碼
新建一個實體類UserInfo,代碼內容沒有什麼特殊的,這裏就不作介紹了,實體類完整代碼以下:sql
package com.dalaoyang.entity;
import org.springframework.data.annotation.Id;
public class UserInfo {
@Id
private Long id;
private String username;
private String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserInfo(Long id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public UserInfo() {
}
}
複製代碼
新建一個UserRepository,由於是響應式編程因此這裏繼承ReactiveMongoRepository,代碼以下:mongodb
package com.dalaoyang.repository;
import com.dalaoyang.entity.UserInfo;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
public interface UserRepository extends ReactiveMongoRepository<UserInfo,Long> {
}
複製代碼
新建一個UserHandler,其中分別建立了四個方法,分別是:數據庫
完整代碼以下:apache
package com.dalaoyang.handler;
import com.dalaoyang.entity.UserInfo;
import com.dalaoyang.repository.UserRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static org.springframework.http.MediaType.APPLICATION_JSON;
@Component
public class UserHandler {
private final UserRepository repository;
public UserHandler(UserRepository repository) {
this.repository = repository;
}
//http://localhost:8888/saveUser
public Mono<ServerResponse> saveUser(ServerRequest request) {
Mono<UserInfo> user = request.bodyToMono(UserInfo.class);
return ServerResponse.ok().build(repository.insert(user).then());
}
//http://localhost:8888/deleteUser/1
public Mono<ServerResponse> deleteUser(ServerRequest request) {
Long userId = Long.valueOf(request.pathVariable("id"));
return ServerResponse.ok().build(repository.deleteById(userId).then());
}
//http://localhost:8888/user/1
public Mono<ServerResponse> getUser(ServerRequest request) {
Long userId = Long.valueOf(request.pathVariable("id"));
Mono<UserInfo> userInfo = repository.findById(userId);
return ServerResponse.ok().contentType(APPLICATION_JSON).body(userInfo, UserInfo.class);
}
//http://localhost:8888/listUser
public Mono<ServerResponse> listUser(ServerRequest request) {
Flux<UserInfo> userList = repository.findAll();
return ServerResponse.ok().contentType(APPLICATION_JSON).body(userList, UserInfo.class);
}
}
複製代碼
在路由中分別配置剛剛寫的4個方法路由跳轉,完整代碼以下:
package com.dalaoyang.router;
import com.dalaoyang.handler.UserHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
@Configuration
public class UserRouter {
@Bean
public RouterFunction<ServerResponse> routeCity(UserHandler userHandler) {
return RouterFunctions
.route(RequestPredicates.GET("/listUser")
.and(RequestPredicates.accept(MediaType.APPLICATION_JSON)),
userHandler::listUser)
.andRoute(RequestPredicates.GET("/user/{id}")
.and(RequestPredicates.accept(MediaType.APPLICATION_JSON)),
userHandler::getUser)
.andRoute(RequestPredicates.GET("/deleteUser/{id}")
.and(RequestPredicates.accept(MediaType.APPLICATION_JSON)),
userHandler::deleteUser)
.andRoute(RequestPredicates.POST("/saveUser")
.and(RequestPredicates.accept(MediaType.APPLICATION_JSON)),
userHandler::saveUser);
}
}
複製代碼
到這一步完成,項目已經構建完成。
本文就不對如何安裝以及啓動MongoDb數據庫進行介紹了,具體能夠查看菜鳥教程,我的以爲這裏已經介紹的很詳細了,而且包含了各個系統的操做。
運行剛剛的項目,這裏以postman測試爲例子,在postman內Post請求保存方法(http://localhost:8888/saveUser),如圖:
而後在請求查詢用戶方法(http://localhost:8888/user/1),如圖所示,證實剛剛已經保存成功,下方body處爲返回數據:
咱們在屢次請求新增用戶方法,將Id分別修改成2,3,4,5並執行保存方法,這裏就不一一截圖,而後方法查詢用戶列表方法(http://localhost:8888/listUser),如圖所示:
最後調用刪除用戶方法(http://localhost:8888/deleteUser/1),這裏以刪除ID爲1的用戶爲例,調用後在查看全部類別如圖,用戶ID爲1的已經被刪除了:
SpringBoot使用WebFlux響應式編程操做Mongodb數據庫這裏已經簡單整合完了,雖然和以前操做數據庫有些不一樣,可是其實大體過程也都類似。
源碼下載 :大老楊碼雲