本指南将引导您完成创建“ 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或更高版本
-
您还可以将代码直接导入到IDE中:
如何完成本指南
像大多数Spring 入门指南一样,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。无论哪种方式,您最终都可以使用工作代码。
要从头开始 ,请继续使用Gradle构建 。
要跳过基础知识 ,请执行以下操作:
-
下载并解压缩本指南的源存储库,或使用Git对其进行克隆:
git clone https://github.com/spring-guides/gs-reactive-rest-service.git
-
光盘进入
gs-reactive-rest-service/initial
-
继续创建WebFlux处理程序 。
完成后 ,您可以根据中的代码检查结果gs-reactive-rest-service/complete
。
用Gradle构建
用Gradle构建
首先,您设置一个基本的构建脚本。在使用Spring构建应用程序时,可以使用任何喜欢的构建系统,但是此处包含使用Gradle和Maven所需的代码。如果您都不熟悉,请参阅使用Gradle 构建Java项目或使用Maven构建Java项目 。
创建目录结构
在您选择的项目目录中,创建以下子目录结构;例如, mkdir -p src/main/java/hello
在* nix系统上:
└── src └── main └── java └── hello
创建一个Gradle构建文件
以下是最初的Gradle构建文件 。
build.gradle
buildscript {
ext {
springBootVersion = '2.1.6.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
bootJar {
baseName = 'gs-reactive-rest-service'
version = '0.1.0'
}
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-webflux')
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile('io.projectreactor:reactor-test')
}
Spring Boot gradle插件提供了许多方便的功能:
-
它收集类路径上的所有jar,并构建一个可运行的单个“über-jar”,这使执行和传输服务更加方便。
-
它搜索
public static void main()
标记为可运行类的方法。 -
它提供了一个内置的依赖项解析器,用于设置版本号以匹配Spring Boot依赖项 。您可以覆盖所需的任何版本,但是它将默认为Boot选择的一组版本。
用Maven构建
用Maven构建
创建目录结构
在您选择的项目目录中,创建以下子目录结构;例如, mkdir -p src/main/java/hello
在* nix系统上:
└── src └── main └── java └── hello
pom.xml
<?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>
<groupId>org.springframework</groupId>
<artifactId>gs-reactive-rest-service</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<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>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Spring Boot Maven插件提供了许多方便的功能:
-
它收集类路径上的所有jar,并构建一个可运行的单个“über-jar”,这使执行和传输服务更加方便。
-
它搜索
public static void main()
标记为可运行类的方法。 -
它提供了一个内置的依赖项解析器,用于设置版本号以匹配Spring Boot依赖项 。您可以覆盖所需的任何版本,但是它将默认为Boot选择的一组版本。
使用您的IDE进行构建
使用您的IDE进行构建
-
阅读如何将本指南直接导入Spring Tool Suite中 。
-
在IntelliJ IDEA中阅读如何使用本指南。
创建一个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.fromObject("Hello, Spring!"));
}
}
这个简单的反应式类始终返回“你好, 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文件以部署到外部应用程序服务器,但是下面演示的更简单的方法创建了一个独立的应用程序。您将所有内容打包在一个可运行的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文件,如下所示:
如果使用Maven,则可以通过使用以下命令运行应用程序./mvnw spring-boot:run
。或者,您可以使用以下命令构建JAR文件: ./mvnw clean package
然后运行JAR文件,如下所示:
此处描述的步骤将创建可运行的JAR。您还可以构建经典的WAR文件 。 |
显示日志记录输出。该服务应在几秒钟内启动并运行。
服务启动后,您将看到以下内容:
>> result = Hello, Spring!
该行来自WebClient正在使用的反应式内容。自然地,您发现与将输出放入System.out相比,您的输出会更有趣。
测试应用
现在该应用程序正在运行,您可以对其进行测试。首先,您可以打开浏览器并转到http://localhost:8080/hello
然后看,“你好, Spring !“对于本指南,我们还创建了一个测试类,以使您开始使用WebTestClient类进行测试。
src/test/java/hello/GreetingRouterTest.java
package hello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(SpringRunner.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应用程序,其中包括一个WebClient来使用RESTful服务!
是否要编写新指南或为现有指南做出贡献?查看我们的贡献准则 。
所有指南均以代码的ASLv2许可证和写作的Attribution,NoDerivatives创作共用许可证发布 。 |