首页 > 其他分享 >构建一个反应式 RESTful Web 服务

构建一个反应式 RESTful Web 服务

时间:2022-12-26 10:02:51浏览次数:40  
标签:Web Spring springframework 反应式 import org RESTful hello 应用程序

构建一个反应式 RESTful Web 服务_java

本指南将引导您完成创建“你好,春天!带有Spring WebFlux的RESTful Web服务(Spring Boot 2.0的新功能),然后使用WebClient使用该服务(也是Spring Boot 2.0的新功能)。

本指南展示了使用 Spring WebFlux 的功能方式。你也可以将注释与 WebFlux 结合使用.

您将构建什么

您将使用 Spring Webflux 和该服务的 WebClient 使用者构建一个 RESTful Web 服务。您将能够在 System.out 和以下位置看到输出:

http://localhost:8080/hello

你需要什么

  • 约15分钟
  • 最喜欢的文本编辑器或 IDE
  • JDK 1.8或以后
  • 格拉德尔 4+​或梅文 3.2+
  • 您也可以将代码直接导入到 IDE 中:
  • 弹簧工具套件 (STS)
  • 智能理念
  • VSCode

如何完成本指南

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

要从头开始,请继续从 Spring 初始化开始.

要跳过基础知识,请执行以下操作:

  • 下载​并解压缩本指南的源存储库,或使用吉特:git clone https://github.com/spring-guides/gs-reactive-rest-service.git
  • 光盘成gs-reactive-rest-service/initial
  • 跳转到创建 WebFlux 处理程序.

完成后,您可以根据 中的代码检查结果。​​gs-reactive-rest-service/complete​

从 Spring 初始化开始

你可以使用这个预初始化项目,然后单击生成以下载 ZIP 文件。此项目配置为适合本教程中的示例。

手动初始化项目:

  1. 导航到https://start.spring.io.此服务拉入应用程序所需的所有依赖项,并为您完成大部分设置。
  2. 选择 Gradle 或 Maven 以及您要使用的语言。本指南假定您选择了 Java。
  3. 单击依赖关系,然后选择 Spring 响应式 Web
  4. 单击生成
  5. 下载生成的 ZIP 文件,该文件是配置了您选择的 Web 应用程序的存档。

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

您也可以从 Github 分叉项目,然后在 IDE 或其他编辑器中打开它。

创建 WebFlux 处理程序

我们将从一个 POJO 开始,它将由我们的 RESTful 服务序列化为 JSON:​​Greeting​

​src/main/java/hello/Greeting.java​

package hello;


public class Greeting {

private String message;

public Greeting() {
}

public Greeting(String message) {
this.message = message;
}

public String getMessage() {
return this.message;
}

public void setMessage(String message) {
this.message = message;
}

@Override
public String toString() {
return "Greeting{" +
"message='" + message + '\'' +
'}';
}
}

在 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.APPLICATION_JSON)
.body(BodyInserters.fromValue(new Greeting("Hello, Spring!")));
}
}

这个简单的反应式类总是返回一个带有“Hello, Spring!”问候语的 JSON 正文。它可以返回许多其他内容,包括数据库中的项流、由计算生成的项流等。请注意反应式代码:一个保存主体的对象。​​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.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;

import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.accept;

@Configuration(proxyBeanMethods = false)
public class GreetingRouter {

@Bean
public RouterFunction<ServerResponse> route(GreetingHandler greetingHandler) {

return RouterFunctions
.route(GET("/hello").and(accept(MediaType.APPLICATION_JSON)), greetingHandler::hello);
}
}

路由器侦听路径上的流量,并返回我们的反应处理程序类提供的值。​​/hello​

创建网络客户端

春季课程本质上是阻塞的。因此,我们不想在反应式应用程序中使用它。对于反应式应用程序,Spring 提供了非阻塞类。我们使用基于 WebClient 的实现来使用我们的 RESTful 服务:​​RestTemplate​​​​WebClient​

​src/main/java/hello/GreetingClient.java​

package hello;

import reactor.core.publisher.Mono;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;

@Component
public class GreetingClient {

private final WebClient client;

// Spring Boot auto-configures a `WebClient.Builder` instance with nice defaults and customizations.
// We can use it to create a dedicated `WebClient` for our component.
public GreetingClient(WebClient.Builder builder) {
this.client = builder.baseUrl("http://localhost:8080").build();
}

public Mono<String> getMessage() {
return this.client.get().uri("/hello").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Greeting.class)
.map(Greeting::getMessage);
}

}

该类使用响应式特征,以 a 的形式保存消息的内容(由方法返回)。这是使用函数 API(而不是命令式 API)来链接反应式运算符。​​WebClient​​​​Mono​​​​getMessage​

可能需要时间来适应反应式接口,但具有有趣的功能,也可用于传统的Spring MVC应用程序。​​WebClient​

您也可以用于与非反应性阻塞服务进行通信。​​WebClient​

使应用程序可执行

我们将使用该方法驱动应用程序并从终结点获取问候消息。​​main()​

​src/main/java/hello/Application.java​

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class Application {

public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
GreetingClient greetingClient = context.getBean(GreetingClient.class);
// We need to block for the content here or the JVM might exit before the message is logged
System.out.println(">> message = " + greetingClient.getMessage().block());
}
}

​@SpringBootApplication​​是一个方便的注释,它添加了以下所有内容:

  • ​@Configuration​​:将类标记为应用程序上下文的 Bean 定义源。
  • ​@EnableAutoConfiguration​​:告诉 Spring 引导根据类路径设置、其他 bean 和各种属性设置开始添加 bean。例如,如果 在类路径上,则此注释会将应用程序标记为 Web 应用程序并激活关键行为,例如设置 .spring-webmvcDispatcherServlet
  • ​@ComponentScan​​:告诉 Spring 在包中查找其他组件、配置和服务,让它找到控制器。hello

该方法使用 Spring Boot 的方法启动应用程序。您是否注意到没有一行 XML?也没有文件。此 Web 应用程序是 100% 纯 Java,您无需处理配置任何管道或基础结构。​​main()​​​​SpringApplication.run()​​​​web.xml​

构建可执行的 JAR

您可以使用 Gradle 或 Maven 从命令行运行应用程序。您还可以构建一个包含所有必需依赖项、类和资源的可执行 JAR 文件并运行该文件。通过构建可执行 jar,可以轻松地在整个开发生命周期中跨不同环境等将服务作为应用程序进行交付、版本控制和部署。

如果使用 Gradle,则可以使用 .或者,您可以使用 JAR 文件生成 JAR 文件,然后运行该文件,如下所示:​​./gradlew bootRun​​​​./gradlew build​

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

如果使用 Maven,则可以使用 运行应用程序。或者,您可以使用 JAR 文件生成 JAR 文件,然后运行该文件,如下所示:​​./mvnw spring-boot:run​​​​./mvnw clean package​

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

此处描述的步骤将创建一个可运行的 JAR。你也可以构建经典 WAR 文件.

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

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

​>> message = Hello, Spring!​

该行来自 WebClient 使用的反应式内容。当然,你可以找到一些比把它放在System.out中更有趣的输出。

测试应用程序

现在应用程序正在运行,您可以对其进行测试。首先,您可以打开浏览器并转到并查看“你好,春天!在本指南中,我们还创建了一个测试类,以帮助您开始使用该类进行测试。​​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;

import static org.assertj.core.api.Assertions.assertThat;

@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.APPLICATION_JSON)
.exchange()
// and use the dedicated DSL to test assertions against the response
.expectStatus().isOk()
.expectBody(Greeting.class).value(greeting -> {
assertThat(greeting.getMessage()).isEqualTo("Hello, Spring!");
});
}
}

总结

祝贺!您已经开发了一个反应式 Spring 应用程序,其中包含一个 Web 客户端来使用 RESTful 服务!

标签:Web,Spring,springframework,反应式,import,org,RESTful,hello,应用程序
From: https://blog.51cto.com/u_15326439/5968600

相关文章

  • 实验八-web部署
    实验内容1.配置openEuler2.安装LAMP3.安装部署wordpress实验步骤购买云服务器本文环境基于华为云的弹性云服务器ECS:CPU架构:选择鲲鹏通用计算增强型操作系统选择......
  • Webrtc audio
    整体理解在WebRTC中,Call是peerconnection的。为WebRTCCall注入的AudioState来自于全局的MediaEngine的VoiceEngine。AudioState是全局的,而Call则是con......
  • Spring Boot中使用Swagger2构建强大的RESTful API文档
    由于SpringBoot能够快速开发、便捷部署等特性,相信有很大一部分SpringBoot的用户会用来构建RESTfulAPI。而我们构建RESTfulAPI的目的通常都是由于多终端的原因,这些终端会......
  • 8款web设计的CSS 工具
    当涉及到简化 css 设计和开发相关的工作时,工具总能创造奇迹。值得指出的是,绝大多数的网页设计者和开发人员对不同的 css 工具都感到兴奋,这些工具能帮助他们更快的制作功......
  • 第八次实验--Web部署
    实验相关配置弹性云服务器ECS远程访问推荐使用MobaXterm.LAMP是指一组通常一起使用来运行动态网站或者服务器的自由软件名称首字母缩写:Linux,操作系统,openEuler就是......
  • 实验八-Web部署
    参考https://www.cnblogs.com/rocedu/p/16929895.html和附件视频,基于LAMP部署wordpress,提交自己部署过程博客1.遇到的问题和解决过程2.对实验的建议配置openEuler在......
  • 实验八-Web部署
    配置openEuler在华为云openEuler安装后,没有配置yum源,我们通过重新配置。cd/etc/yum.repos.d  增加下面内容:[OS]name=OSbaseurl=http://repo.openeuler.org/openE......
  • 14款web前端常用的富文本编辑器插件
    富文本编辑器是一种可内嵌于浏览器,所见即所得的文本编辑器。它提供类似于OfficeWord的编辑功能,方便那些不太懂html用户使用,富文本编辑器的应用非常广泛,它的历史与图文网页......
  • 20221414徐鹿鸣的实验八-Web部署
    过程与老师博客基本相同。(之前卡崩了导致没截图)遇到的问题和解决过程1.如何退出MariaDBexit2.如何退出编辑Apache的配置文件以nano开头编辑文件的,则要退出,按【Ctr......
  • 如何用webgl(three.js)搭建一个3D库房,3D仓库3D码头,3D集装箱,车辆定位,叉车定位可视
    使用three.js(webgl)搭建智慧楼宇、3D园区、3D厂房、3D码头、3D海关、3D仓库、3D定位、三维室内定位、设备检测、数字孪生、物联网3D、物业3D监控、物业......