# 構建反應式RESTful Web服務
本指南將引導您完成創建“ Hello,Spring!”的過程。 帶有Spring WebFlux(版本5的新功能)的RESTful Web服務,然后通過WebClient(版本5的新功能)使用該服務。
本指南展示了使用Spring WebFlux的功能方法。 您還可以 將注釋與WebFlux一起使用 。
## 你會建立什么
您將使用Spring Webflux和該服務的WebClient使用者構建RESTful Web服務。 您將能夠在System.out和以下位置看到輸出:
~~~
http://localhost:8080/hello
~~~
## 您將需要什么
* 約15分鐘
* 最喜歡的文本編輯器或IDE
* [JDK 1.8](http://www.oracle.com/technetwork/java/javase/downloads/index.html) 或更高版本
* [Gradle 4+](http://www.gradle.org/downloads) 或 [Maven 3.2+](https://maven.apache.org/download.cgi)
* 您還可以將代碼直接導入到IDE中:
* [彈簧工具套件(STS)](https://spring.io/guides/gs/sts)
* [IntelliJ IDEA](https://spring.io/guides/gs/intellij-idea/)
## 如何完成本指南
像大多數Spring 一樣 [入門指南](https://spring.io/guides) ,您可以從頭開始并完成每個步驟,也可以繞過您已經熟悉的基本設置步驟。 無論哪種方式,您最終都可以使用代碼。
要 **從頭開始** ,請繼續進行“ [從Spring Initializr開始”](https://spring.io/guides/gs/reactive-rest-service/#scratch) 。
要 **跳過基礎知識** ,請執行以下操作:
* [下載](https://github.com/spring-guides/gs-reactive-rest-service/archive/master.zip) 并解壓縮本指南的源存儲庫,或使用 對其進行克隆 [Git](https://spring.io/understanding/Git) : `git clone [https://github.com/spring-guides/gs-reactive-rest-service.git](https://github.com/spring-guides/gs-reactive-rest-service.git)`
* 光盤進入 `gs-reactive-rest-service/initial`
* 繼續 [創建WebFlux處理程序](https://spring.io/guides/gs/reactive-rest-service/#initial) 。
**完成后** ,您可以根據中的代碼檢查結果 `gs-reactive-rest-service/complete`.
## 從Spring Initializr開始
如果您使用Maven,請訪問 [Spring Initializr](https://start.spring.io/#!type=maven-project&language=java&platformVersion=2.4.3.RELEASE&packaging=jar&jvmVersion=1.8&groupId=com.example&artifactId=reactive-rest-service&name=reactive-rest-service&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.reactive-rest-service&dependencies=webflux) 以生成具有所需依賴項的新項目(Spring Web Reactive)。
以下清單顯示了 `pom.xml` 選擇Maven時創建的文件:
~~~
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>reactive-rest-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>reactive-rest-service</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</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>
~~~
如果您使用Gradle,請訪問 [Spring Initializr](https://start.spring.io/#!type=gradle-project&language=java&platformVersion=2.4.3.RELEASE&packaging=jar&jvmVersion=1.8&groupId=com.example&artifactId=reactive-rest-service&name=reactive-rest-service&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.reactive-rest-service&dependencies=webflux) 以生成具有所需依賴項的新項目(Spring Web Reactive)。
以下清單顯示了 `build.gradle` 選擇Gradle時創建的文件:
~~~
plugins {
id 'org.springframework.boot' version '2.4.3'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-webflux'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'io.projectreactor:reactor-test'
}
test {
useJUnitPlatform()
}
~~~
### 手動初始化(可選)
如果要手動初始化項目而不是使用前面顯示的鏈接,請按照以下步驟操作:
1. 導航到 [https://start.spring.io](https://start.spring.io) 。 該服務提取應用程序所需的所有依賴關系,并為您完成大部分設置。
2. 選擇Gradle或Maven以及您要使用的語言。 本指南假定您選擇了Java。
3. 單擊 **Dependencies,** 然后選擇 **Spring Reactive Web** 。
4. 點擊 **生成** 。
5. 下載生成的ZIP文件,該文件是使用您的選擇配置的Web應用程序的存檔。
如果您的IDE集成了Spring Initializr,則可以從IDE中完成此過程。
## 創建一個WebFlux處理程序
在Spring Reactive方法中,我們使用處理程序來處理請求并創建響應,如以下示例所示:
`src/main/java/hello/GreetingHandler.java`
~~~
package hello;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
@Component
public class GreetingHandler {
public Mono<ServerResponse> hello(ServerRequest request) {
return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN)
.body(BodyInserters.fromValue("Hello, Spring!"));
}
}
~~~
這個簡單的反應式類始終返回“ Hello,Spring!”。 它可能返回許多其他內容,包括來自數據庫的項目流,通過計算生成的項目流,等等。 請注意反應性代碼: `Mono` 持有一個的對象 `ServerResponse` 身體。
## 創建一個路由器
在此應用程序中,我們使用路由器來處理我們公開的唯一路由( `/hello`),如以下示例所示:
`src/main/java/hello/GreetingRouter.java`
~~~
package hello;
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 GreetingRouter {
@Bean
public RouterFunction<ServerResponse> route(GreetingHandler greetingHandler) {
return RouterFunctions
.route(RequestPredicates.GET("/hello").and(RequestPredicates.accept(MediaType.TEXT_PLAIN)), greetingHandler::hello);
}
}
~~~
路由器偵聽路由器上的流量 `/hello` 路徑并返回我們的反應性處理程序類提供的值。
## 創建一個WebClient
Spring MVC RestTemplate類本質上是阻塞的。 因此,我們不想在反應性應用程序中使用它。 對于反應性應用,Spring提供了 `WebClient`類,這是非阻塞的。 我們使用WebClient實現來使用我們的RESTful服務:
`src/main/java/hello/GreetingWebClient.java`
~~~
package hello;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
public class GreetingWebClient {
private WebClient client = WebClient.create("http://localhost:8080");
private Mono<ClientResponse> result = client.get()
.uri("/hello")
.accept(MediaType.TEXT_PLAIN)
.exchange();
public String getResult() {
return ">> result = " + result.flatMap(res -> res.bodyToMono(String.class)).block();
}
}
~~~
這 `WebClient` 類使用反應性功能,形式為 `Mono` 來保存我們指定的URI的內容和一個函數(在 `getResult`方法)將內容轉換為字符串。 如果我們有不同的要求,則可以將其轉換為字符串以外的形式。 因為我們要把結果放入 `System.out`,字符串在這里起作用。
您可以使用 WebClient 與非反應式阻塞服務進行通信。
## 使應用程序可執行
盡管您可以將此服務打包為傳統的 [WAR](https://spring.io/understanding/WAR) 文件,以部署到外部應用程序服務器,但是下面演示的更簡單的方法創建了一個獨立的應用程序。 您將所有內容打包在一個可執行的JAR文件中,由一個好的舊Java驅動 `main()`方法。 在此過程中,您使用Reactive Spring的支持將Netty服務器作為HTTP運行時嵌入,而不是部署到外部實例。
`src/main/java/hello/Application.java`
~~~
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
GreetingWebClient gwc = new GreetingWebClient();
System.out.println(gwc.getResult());
}
}
~~~
`@SpringBootApplication` 是一個方便注釋,它添加了以下所有內容:
* `@Configuration`:將類標記為應用程序上下文的Bean定義的源。
* `@EnableAutoConfiguration`:告訴Spring Boot根據類路徑設置,其他bean和各種屬性設置開始添加bean。 例如,如果 `spring-webmvc` 在類路徑上,此注釋將應用程序標記為Web應用程序并激活關鍵行為,例如設置 `DispatcherServlet`.
* `@ComponentScan`:告訴Spring在服務器中尋找其他組件,配置和服務 `hello` 包,讓它找到控制器。
這 `main()` 方法使用Spring Boot的 `SpringApplication.run()`啟動應用程序的方法。 您是否注意到沒有一行XML? 沒有 `web.xml`文件。 該Web應用程序是100%純Java,因此您無需處理任何管道或基礎結構。
### 建立可執行的JAR
您可以使用Gradle或Maven從命令行運行該應用程序。 您還可以構建一個包含所有必需的依賴項,類和資源的可執行JAR文件,然后運行該文件。 生成可執行jar使得在整個開發生命周期中,跨不同環境等等的情況下,都可以輕松地將服務作為應用程序進行發布,版本控制和部署。
如果您使用Gradle,則可以通過使用以下命令運行該應用程序 `./gradlew bootRun`。 或者,您可以通過使用以下命令構建JAR文件: `./gradlew build` 然后運行JAR文件,如下所示:
~~~
java -jar build/libs/gs-reactive-rest-service-0.1.0.jar
~~~
如果您使用Maven,則可以通過使用以下命令運行該應用程序 `./mvnw spring-boot:run`。 或者,您可以使用以下命令構建JAR文件: `./mvnw clean package` 然后運行JAR文件,如下所示:
~~~
java -jar target/gs-reactive-rest-service-0.1.0.jar
~~~
此處描述的步驟將創建可運行的JAR。 您還可以 構建經典的WAR文件 。
顯示日志記錄輸出。 該服務應在幾秒鐘內啟動并運行。
服務啟動后,您會看到以下內容:
`>> result = Hello, Spring!`
該行來自WebClient正在使用的反應式內容。 自然,與將輸出放入System.out相比,您會發現與輸出更有趣的事情。
## 測試應用
現在該應用程序正在運行,您可以對其進行測試。 首先,您可以打開瀏覽器并轉到 `[http://localhost:8080/hello](http://localhost:8080/hello)`然后看,“你好,春天!” 在本指南中,我們還創建了一個測試類,以幫助您開始使用 `WebTestClient` 班級。
`src/test/java/hello/GreetingRouterTest.java`
~~~
package hello;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.reactive.server.WebTestClient;
@ExtendWith(SpringExtension.class)
// We create a `@SpringBootTest`, starting an actual server on a `RANDOM_PORT`
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class GreetingRouterTest {
// Spring Boot will create a `WebTestClient` for you,
// already configure and ready to issue requests against "localhost:RANDOM_PORT"
@Autowired
private WebTestClient webTestClient;
@Test
public void testHello() {
webTestClient
// Create a GET request to test an endpoint
.get().uri("/hello")
.accept(MediaType.TEXT_PLAIN)
.exchange()
// and use the dedicated DSL to test assertions against the response
.expectStatus().isOk()
.expectBody(String.class).isEqualTo("Hello, Spring!");
}
}
~~~
## 概括
恭喜你! 您已經開發了一個Reactive Spring應用程序,其中包括一個使用RESTful服務的WebClient!
- springboot概述
- springboot構建restful服務
- spring構建一個RESTful Web服務
- spring定時任務
- 消費RESTful Web服務
- gradle構建項目
- maven構建項目
- springboot使用jdbc
- springboot應用上傳文件
- 使用LDNA驗證用戶
- 使用 spring data redis
- 使用 spring RabbitTemplate消息隊列
- 用no4j訪問nosql數據庫
- springboot驗證web表單
- Spring Boot Actuator構j建服務
- 使用jms傳遞消息
- springboot創建批處理服務
- spring security保護web 安全
- 在Pivotal GemFire中訪問數據
- 使用Spring Integration
- 使用springboot jpa進行數據庫操作
- 數據庫事務操作
- 操作mongodb
- springmvc+tymleaf創建web應用
- 將Spring Boot JAR應用程序轉換為WAR
- 創建異步服務
- spring提交表單
- 使用WebSocket構建交互式Web應用程序
- 使用REST訪問Neo4j數據
- jquery消費restful
- springboot跨域請求
- 消費SOAP Web服務
- springboot使用緩存
- 使用Vaadin創建CRUD UI
- 使用REST訪問JPA數據
- 使用REST訪問Pivotal GemFire中的數據
- 構建soap服務
- 使用rest訪問mongodb數據
- 構建springboot應用docker鏡像
- 從STS部署到Cloud Foundry
- springboot測試web應用
- springboot訪問mysql
- springboot編寫自定義模塊并使用
- 使用Google Cloud Pub / Sub進行消息傳遞
- 構建反應式RESTful Web服務
- 使用Redis主動訪問數據
- Spring Boot 部署到Kubernetes
- 使用反應式協議R2DBC訪問數據
- Spring Security架構
- spring構建Docker鏡像詳解
- Spring Boot和OAuth2
- springboot應用部署到k8s
- spring構建rest服務詳解