3年前 (2021-04-03)  相关技术 |   抢沙发  387 
文章评分 0 次,平均分 0.0

使用Spring WebFlux构建响应式web服务

本文将介绍如何创建“Hello,Spring!”的一个响应式应用,使用Spring WebFlux的restfulweb服务(从版本5开始新增),然后使用WebClient使用该服务(从版本5开始新增)。

关于Spring WebFlux的功能方法可以参考这篇文章:https://javakk.com/1783.html

您将使用Spring WebFlux和该服务的WebClient使用者构建一个restfulweb服务。您将能够看到这两个方面的输出系统输出地址:

http://localhost:8080/hello

运行环境:

  • JDK 1.8或更高版本
  • Gradle 4+或Maven 3.2+
  • Spring Tool Suite(STS)
  • IntelliJ IDEA

像大多数Spring入门指南一样,您可以从头开始并完成每个步骤,也可以跳过您已经熟悉的基本设置步骤。无论哪种方式,最终都会得到工作代码。

要从头开始,请继续从Spring initializer开始。

要跳过基本内容,请执行以下操作:

  • 使用Git:Git clone进行克隆:https://github.com/spring-guides/gs-reactive-rest-service.git
  • cd进入gs-reactive-rest-service/initial
  • 跳到前面来创建WebFlux处理程序。

完成后,可以对照gs-reactive-rest-service/complete中的代码检查结果。

从Spring Initializr开始

如果您使用Maven,请访问Spring初始化器:https://start.spring.io 以生成具有所需依赖项的新项目。

下面的清单显示了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>

手动初始化(可选)

如果要手动初始化项目,而不是使用前面显示的链接,请执行以下步骤:

1. 导航到https://start.spring.io。这个服务会为应用程序提供所需的所有依赖项,并为您完成大部分设置。

2. 选择Gradle或Maven以及您想要使用的语言。本指南假设您选择了Java。

3. 单击Dependencies并选择Spring Reactive Web。

4. 单击“生成”。

5. 下载生成的ZIP文件,它是使用您的选择配置的web应用程序的存档。

如果您的IDE集成了Spring Initializer,则可以从IDE完成此过程。

创建WebFlux处理程序

在Spring反应式方法中,我们使用处理程序处理请求并创建响应,如下例所示:

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!”它可以返回许多其他东西,包括来自数据库的项目流、通过计算生成的项目流等等。请注意反应式代码:一个保存ServerResponse主体的Mono对象。

创建路由器

在此应用程序中,我们使用路由器来处理我们公开的唯一路由(/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方法中)将该内容转换为字符串。如果我们有不同的需求,我们可能会把它变成字符串以外的东西。既然我们想把结果放到系统输出,字符串在这里起作用。

您也可以使用WebClient与非反应式、阻塞式服务进行通信。

使应用程序可执行

尽管您可以将此服务打包为传统的WAR文件以部署到外部应用程序服务器,但下面演示的更简单的方法将创建一个独立的应用程序。您可以将所有内容打包到一个可执行的JAR文件中,由一个好的老java main()方法驱动。在此过程中,您将使用reactivespring支持将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:告诉springboot根据类路径设置、其他bean和各种属性设置开始添加bean。例如,如果springwebmvc位于类路径上,则此注释将应用程序标记为web应用程序,并激活关键行为,例如设置DispatcherServlet
  • @ComponentScan:告诉Spring在hello包中寻找其他组件、配置和服务,让它找到控制器。

main()方法使用Spring Boot的SpringApplication.run()启动应用程序的方法。您注意到没有一行XML吗?根本没有web.xml文件也一样。这个web应用程序是100%纯Java,您不必配置任何管道或基础设施。

构建可执行JAR

您可以使用Gradle或Maven从命令行运行应用程序。您还可以构建一个包含所有必要依赖项、类和资源的可执行JAR文件并运行它。构建一个可执行jar使得在整个开发生命周期、不同的环境中,将服务作为一个应用程序进行发布、版本设置和部署变得非常容易。

如果使用Gradle,可以使用./gradlew bootRun运行应用程序。或者,可以使用./gradlew build构建JAR文件,然后运行JAR文件,如下所示:

java -jar build/libs/gs-reactive-rest-service-0.1.0.jar

如果使用Maven,则可以使用./mvnw-spring运行spring-boot:run。或者,可以使用./mvnw clean package构建JAR文件,然后运行JAR文件,如下所示:

java -jar target/gs-reactive-rest-service-0.1.0.jar

这里描述的步骤创建一个可运行的JAR。您还可以构建一个经典的WAR文件。

显示日志输出。服务应该在几秒钟内启动并运行。

服务启动后,您可以看到一行内容:

>> result = Hello, Spring!

该行来自WebClient正在使用的反应性内容。当然,你可以找到一些更有趣的事情来处理你的输出,而不是把它放进去系统输出.

测试应用程序

现在应用程序正在运行,您可以测试它了。首先,您可以打开浏览器并转到http://localhost:8080/你好,看,“Hello, Spring!”对于本指南,我们还创建了一个测试类,让您开始使用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!");
  }
}

至此我们已经开发了一个简单的反应式Spring应用程序,其中包含一个WebClient来使用RESTful服务。

 

除特别注明外,本站所有文章均为老K的Java博客原创,转载请注明出处来自https://javakk.com/1789.html

关于

发表评论

表情 格式

暂无评论

登录

忘记密码 ?

切换登录

注册