Spring WebFlux - Spring 响应式编程

2023-11-15

Spring WebFlux是Spring 5中引入的新模块。Spring WebFlux是Spring框架中向反应式编程模型迈出的第一步。

Spring 响应式编程

如果您是反应式编程模型的新手,那么我强烈建议您阅读以下文章来了解反应式编程。

  • 反应式宣言
  • 反应式流
  • Java 9 反应式流
  • RxJava

如果您是 Spring 5 的新手,请浏览Spring 5 特点.

Spring WebFlux

Spring WebFlux is the alternative to Spring MVC module. Spring WebFlux is used to create fully asynchronous and non-blocking application built on event-loop execution model. Below diagram from Spring Official Documentation provides great insight on comparison of Spring WebFlux to Spring Web MVC. spring webflux and spring mvc If you are looking to develop a web application or Rest web service on non-blocking reactive model, then you can look into Spring WebFlux. Spring WebFlux is supported on Tomcat, Jetty, Servlet 3.1+ containers, as well as on non-Servlet runtimes such as Netty and Undertow. Spring WebFlux is built on Project Reactor. Project Reactor is the implementation of Reactive Streams specification. Reactor provides two types:

  1. Mono:实现 Publisher 并返回 0 或 1 个元素
  2. Flux:实现 Publisher 并返回 N 个元素。

Spring WebFlux Hello World 示例

Let’s built a simple Spring WebFlux Hello World application. We will create a simple rest web service and use Spring Boot to run it on default Netty server. Our final project structure looks like below image. spring webflux example Let’s look into each component of the application one by one.

Spring WebFlux Maven 依赖项

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.journaldev.spring</groupId>
  <artifactId>SpringWebflux</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>Spring WebFlux</name>
  <description>Spring WebFlux Example</description>
  
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <jdk.version>1.9</jdk.version>
    </properties>
    
  <parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.1.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>
	<repositories>
		<repository>
			<id>spring-snapshots</id>
			<name>Spring Snapshots</name>
			<url>https://repo.spring.io/snapshot</url>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</repository>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>
	<pluginRepositories>
		<pluginRepository>
			<id>spring-snapshots</id>
			<name>Spring Snapshots</name>
			<url>https://repo.spring.io/snapshot</url>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</pluginRepository>
		<pluginRepository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</pluginRepository>
	</pluginRepositories>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.7.0</version>
                    <configuration>
                        <source>${jdk.version}</source>
                        <target>${jdk.version}</target>
                    </configuration>
                </plugin>
            </plugins>
    </pluginManagement>
    </build>
    
</project>

最重要的依赖项是spring-boot-starter-webflux and spring-boot-starter-parent。其他一些依赖项用于创建 JUnit 测试用例。

Spring WebFlux 处理程序

Spring WebFlux Handler方法处理请求并返回Mono or Flux作为回应。

package com.journaldev.spring.component;

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 HelloWorldHandler {

	public Mono<ServerResponse> helloWorld(ServerRequest request) {
		return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN)
			.body(BodyInserters.fromObject("Hello World!"));
	}
}

注意电抗组件Mono持有ServerResponse身体。另请查看函数链以设置返回内容类型、响应代码和正文。

Spring WebFlux 路由器

路由器方法用于定义应用程序的路由。这些方法返回RouterFunction也持有的对象ServerResponse body.

package com.journaldev.spring.component;

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 HelloWorldRouter {

	@Bean
	public RouterFunction<ServerResponse> routeHelloWorld(HelloWorldHandler helloWorldHandler) {

		return RouterFunctions.route(RequestPredicates.GET("/helloWorld")
                .and(RequestPredicates.accept(MediaType.TEXT_PLAIN)), helloWorldHandler::helloWorld);
	}
}

所以我们公开了一个 GET 方法/helloWorld并且客户端调用应该接受纯文本响应。

Spring引导应用程序

让我们使用 Spring Boot 配置简单的 WebFlux 应用程序。

package com.journaldev.spring;

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);
	}
}

如果你看上面的代码,没有任何与 Spring WebFlux 相关的内容。但是 Spring Boot 会将我们的应用程序配置为 Spring WebFlux,因为我们添加了依赖项spring-boot-starter-webflux module.

Java 9 模块支持

我们的应用程序已准备好在 Java 8 上执行,但如果您使用的是 Java 9,那么我们还需要添加module-info.java class.

module com.journaldev.spring {
    requires reactor.core;
    requires spring.web;
    requires spring.beans;
    requires spring.context;
    requires spring.webflux;
    requires spring.boot;
    requires spring.boot.autoconfigure;
    exports com.journaldev.spring;
}

运行 Spring WebFlux Spring Boot 应用程序

If you have Spring support in Eclipse, then you can run above class as Spring Boot App. Eclipse run as spring boot app If you like to use command line, then open terminal and run command mvn spring-boot:run from the project source directory. Once the app is running, notice following log messages to make sure everything is good with our app. It’s also helpful when you extend this simple app by adding more routes and functionalities.

2018-05-07 15:01:47.893  INFO 25158 --- [           main] o.s.w.r.f.s.s.RouterFunctionMapping      : Mapped ((GET && /helloWorld) && Accept: [text/plain]) -> com.journaldev.spring.component.HelloWorldRouter$$Lambda$501/704766954@6eeb5d56
2018-05-07 15:01:48.495  INFO 25158 --- [ctor-http-nio-1] r.ipc.netty.tcp.BlockingNettyContext     : Started HttpServer on /0:0:0:0:0:0:0:0:8080
2018-05-07 15:01:48.495  INFO 25158 --- [           main] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port(s): 8080
2018-05-07 15:01:48.501  INFO 25158 --- [           main] com.journaldev.spring.Application        : Started Application in 1.86 seconds (JVM running for 5.542)

从日志中可以清楚地看出,我们的应用程序正在 Netty 服务器的端口 8080 上运行。让我们继续测试我们的应用程序。

Spring WebFlux 应用程序测试

我们可以使用各种方法来测试我们的应用程序。

  1. 使用 CURL 命令

    $ curl https://localhost:8080/helloWorld
    Hello World!
    $ 
    
  2. Launch URL in Browser spring webflux restful web service test

  3. 从 Spring 5 使用 WebTestClient这是一个 JUnit 测试程序,用于使用以下命令来测试我们的 Rest Web 服务WebTestClient来自 Spring 5 反应式网络。

    package com.journaldev.spring;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    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;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    public class SpringWebFluxTest {
    
    	@Autowired
    	private WebTestClient webTestClient;
    
    	
    	@Test
    	public void testHelloWorld() {
    		webTestClient
    		.get().uri("/helloWorld") // GET method and URI
    		.accept(MediaType.TEXT_PLAIN) //setting ACCEPT-Content
    		.exchange() //gives access to response
    		.expectStatus().isOk() //checking if response is OK
    		.expectBody(String.class).isEqualTo("Hello World!"); // checking for response type and message
    	}
    
    }
    

    Run it a JUnit test case and it should pass with flying colors. Spring Reactive WebTestClient example JUnit test case

  4. 使用 Spring Web Reactive 中的 WebClient我们还可以使用WebClient打电话给REST 网络服务.

    package com.journaldev.spring.client;
    
    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 HelloWorldWebClient {
    
    	public static void main(String args[]) {
    		WebClient client = WebClient.create("https://localhost:8080");
    
    		Mono<ClientResponse> result = client.get()
    				.uri("/helloWorld")
    				.accept(MediaType.TEXT_PLAIN)
    				.exchange();
    
    			System.out.println("Result = " + result.flatMap(res -> res.bodyToMono(String.class)).block());
    	}
    	
    }
    

    Just run it as a simple java application and you should see the proper output with a lot of debug messages. spring reactive web WebClient example

Summary

在这篇文章中,我们了解了 Spring WebFlux 以及如何构建 hello world 反应式 Restful Web 服务。很高兴看到 Spring 等流行框架都支持响应式编程模型。但我们有很多内容要介绍,因为如果您的所有依赖项都不是响应式且非阻塞的,那么您的应用程序也不是真正的响应式。例如,关系数据库供应商没有反应式驱动程序,因为它们依赖于 JDBC,而后者不是反应式的。因此 Hibernate API 也是非响应式的。因此,如果您使用关系数据库,那么您还无法构建真正的反应式应用程序。我希望这种情况能够尽快改变。

您可以从我的下载项目代码GitHub 存储库.

参考:官方文档

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring WebFlux - Spring 响应式编程 的相关文章

随机推荐

  • 如何在 CentOS 7 上安装 Plex 媒体服务器

    Plex 是一款流媒体服务器 可将您所有的视频 音乐和照片收藏集中在一起 并随时随地将它们流式传输到您的设备 在本教程中 我们将向您展示如何安装和配置Plex 媒体服务器在 CentOS 7 上 先决条件 在继续本教程之前 请确保您以以下身
  • Linux 中的 df 命令(检查磁盘空间)

    我的硬盘还剩多少空间 是否有足够的可用磁盘空间来下载大文件或安装新应用程序 在 Linux 和 Unix 操作系统上 您可以使用df命令获取有关系统磁盘空间使用情况的详细报告 使用 df 命令 的一般语法为df命令如下 df OPTIONS
  • 如何在 CentOS 8 上安装 Node.js 和 npm

    Node js 是一个基于 Chrome JavaScript 构建的跨平台 JavaScript 运行时环境 旨在在服务器端执行 JavaScript 代码 使用 Node js 您可以构建可扩展的网络应用程序 npm 是 Node Pa
  • 如何在 Debian 9 上安装 Webmin

    Webmin是一个用于管理 Linux 服务器的开源 Web 控制面板 使用 Webmin 您可以管理系统用户 组 磁盘配额以及配置最流行的服务 包括 Web ssh ftp 电子邮件和数据库服务器 本教程介绍如何在 Debian Linu
  • 如何在 Debian 11 上为专用连接设置 Squid 代理

    介绍 代理服务器是一种服务器应用程序 充当最终用户和互联网资源之间的网关 通过代理服务器 最终用户能够出于多种目的控制和监视其 Web 流量 包括隐私 安全和缓存 例如 您可以使用代理服务器从与您自己的 IP 地址不同的 IP 地址发出 W
  • 如何在 Ubuntu 16.04 上安装 MySQL

    介绍 MySQL是一个开源数据库管理系统 通常作为流行的一部分安装LAMP Linux Apache MySQL PHP Python Perl 堆栈 它使用关系数据库和 SQL 结构化查询语言 来管理其数据 简短版本的安装很简单 更新您的
  • Java IO 教程

    Java提供了几个类java io用于处理文本 流数据和文件系统的包 我最近提供了几个有关 Java 文件和 Java IO 的示例 这篇文章是所有 Java IO 文章的索引 Java IO 如何在 Java 中创建新文件在这篇文章中 您
  • Java Stream Collect() 方法示例

    Java Streamcollect 对流的元素执行可变归约操作 这是终端操作 什么是可变约简操作 可变归约操作处理流元素 然后将其累积到可变结果容器中 处理元素后 组合函数将合并所有结果容器以创建结果 Java Stream Collec
  • 快速初始化()

    在本 Swift 教程中 我们将讨论一个重要的概念 即 Swift init 或 Swift 初始化 初始化是当我们创建某种类型的实例时发生的事情 快速初始化 初始化是准备类 结构或枚举的实例以供使用的过程 此过程涉及为该实例上的每个存储属
  • 如何在 Debian Wheezy 上使用 Postfix 安装和配置 DKIM

    介绍 对于大多数邮件服务器管理员来说 被错误地标记为垃圾邮件发送者所带来的挫败感并不奇怪 通过排除服务器受损的可能性 错误标记通常是由以下原因之一引起的 该服务器是一个开放的邮件中继 发件人或服务器的 IP 地址已列入黑名单 服务器没有完全
  • Linux/Unix 中的 AWK 命令

    AWK 适用于模式搜索和处理 该脚本运行以搜索一个或多个文件以识别匹配模式以及所述模式是否执行特定任务 在本指南中 我们将了解 AWK Linux 命令并了解它的功能 AWK 可以执行哪些操作 逐行扫描文件 将每个输入行拆分为字段 将输入行
  • 如何在 Python 中将字符串转换为日期时间或时间对象

    介绍 蟒蛇datetime and time模块均包括strptime 将字符串转换为对象的类方法 在本文中 您将使用strptime 将字符串转换为datetime and struct time 对象 将字符串转换为datetime对象
  • 如何在 Ubuntu 18.04 上使用 Python 3 设置 Jupyter Notebook

    介绍 Jupyter笔记本是一个开源 Web 应用程序 可让您创建和共享交互式代码 可视化等 该工具可与多种编程语言一起使用 包括 Python Julia R Haskell 和 Ruby 它通常用于处理数据 统计建模和机器学习 本教程将
  • 了解 Vue.js 生命周期挂钩

    介绍 生命周期挂钩是了解您正在使用的库如何在幕后工作的窗口 生命周期钩子允许您知道组件何时被创建 添加到 DOM 更新或销毁 本文将向您介绍 Vue js 中的创建 安装 更新和销毁钩子 先决条件 要完成本教程 您需要 熟悉 Vue js
  • Java 单例类中的线程安全

    Singleton 是最广泛使用的创建型设计模式之一 用于限制应用程序创建的对象 如果是在多线程环境中使用 那么单例类的线程安全性就非常重要 在现实应用程序中 数据库连接或企业信息系统 EIS 等资源是有限的 应明智地使用以避免任何资源紧缩
  • Fail2Ban 如何保护 Linux 服务器上的服务

    介绍 SSH 是连接云服务器的事实上的方法 它耐用且可扩展 随着新的加密标准的开发 它们可用于生成新的 SSH 密钥 确保核心协议保持安全 然而 没有任何协议或软件堆栈是完全万无一失的 SSH 在互联网上如此广泛的部署意味着它代表了一种非常
  • 如何在运行 Ubuntu 的 VPS 上安装和使用 Composer

    Status 已弃用 本文介绍不再受支持的 Ubuntu 版本 如果您当前运行的服务器运行 Ubuntu 12 04 我们强烈建议您升级或迁移到受支持的 Ubuntu 版本 升级到Ubuntu 14 04 从 Ubuntu 14 04 升级
  • 如何在 Rocky Linux 9 上安装 Node.js

    介绍 Node js是用于服务器端编程的 JavaScript 运行时 它允许开发人员使用 JavaScript 创建可扩展的后端功能 这是许多人在基于浏览器的 Web 开发中已经熟悉的语言 在本指南中 您将了解在 Rocky Linux
  • Java 堆空间与堆栈 - Java 中的内存分配

    不久前我写了几篇关于Java 垃圾收集 and Java 是按值传递 之后我收到了很多电子邮件来解释Java堆空间 Java堆栈内存 Java中的内存分配它们之间有什么区别 您会在 Java Java EE 书籍和教程中看到很多对堆和堆栈内
  • Spring WebFlux - Spring 响应式编程

    Spring WebFlux是Spring 5中引入的新模块 Spring WebFlux是Spring框架中向反应式编程模型迈出的第一步 Spring 响应式编程 如果您是反应式编程模型的新手 那么我强烈建议您阅读以下文章来了解反应式编程