SpringBoot中的响应式web应用
简介
在Spring 5中,Spring MVC引入了webFlux的概念,webFlux的底层是基于reactor-netty来的,而reactor-netty又使用了Reactor库。
本文将会介绍在Spring Boot中reactive在WebFlux中的使用。
Reactive in Spring
前面我们讲到了,webFlux的基础是Reactor。 于是Spring Boot其实拥有了两套不同的web框架,第一套框架是基于传统的Servlet API和Spring MVC,第二套是基于最新的reactive框架,包括 Spring WebFlux 和Spring Data的reactive repositories。
我们用上面的一张图可以清晰的看到两套体系的不同。
对于底层的数据源来说,MongoDB, Redis, 和 Cassandra 可以直接以reactive的方式支持Spring Data。而其他很多关系型数据库比如Postgres, Microsoft SQL Server, MySQL, H2 和 Google Spanner 则可以通过使用R2DBC 来实现对reactive的支持。
而Spring Cloud Stream甚至可以支持RabbitMQ和Kafka的reactive模型。
下面我们将会介绍一个具体的Spring Boot中使用Spring WebFlux的例子,希望大家能够喜欢。
注解方式使用WebFlux
要使用Spring WebFlux,我们需要添加如下的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
只用注解的方式和普通的Spring MVC的方式很类似,我们可以使用@RestController表示是一个rest服务,可以使用 @GetMapping("/hello") 来表示一个get请求。
不同之处在于,我们请求的产生方式和返回值。
熟悉Reactor的朋友可能都知道,在Reactor中有两种产生序列的方式,一种是Flux一种是Mono,其中Flux表示1或者多,而Mono表示0或者1。
看一下我们的Controller该怎么写:
@RestController
public class WelcomeController {
@GetMapping("/hello")
public Mono<String> hello() {
return Mono.just("www.flydean.com");
}
@GetMapping("/hellos")
public Flux<String> getAll() {
//使用lambda表达式
return Flux.fromStream(Stream.of("www.flydean.com","flydean").map(String::toLowerCase));
}
}
这个例子中,我们提供了两个get方法,第一个是hello,直接使用Mono.just返回一个Mono。
第二个方法是hellos,通过Flux的一系列操作,最后返回一个Flux对象。
有了Mono对象,我们怎么取出里面的数据呢?
public class WelcomeWebClient {
private WebClient client = WebClient.create("http://localhost:8080");
private final 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来获取get的结果,通过exchange将其转换为ClientResponse。
然后提供了一个getResult方法从result中获取最终的返回结果。
这里,我们先调用FlatMap对ClientResponse进行转换,然后再调用block方法,产生一个新的subscription。
最后,我们看一下Spring Boot的启动类:
@Slf4j
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
WelcomeWebClient welcomeWebClient = new WelcomeWebClient();
log.info("react result is {}",welcomeWebClient.getResult());
}
}
编程方式使用webFlux
刚刚的注解方式其实跟我们常用的Spring MVC基本上是一样的。
接下来,我们看一下,如果是以编程的方式来编写上面的逻辑应该怎么处理。
首先,我们定义一个处理hello请求的处理器:
@Component
public class WelcomeHandler {
public Mono<ServerResponse> hello(ServerRequest request) {
return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN)
.body(BodyInserters.fromValue("www.flydean.com!"));
}
}
和普通的处理一样,我们需要返回一个Mono对象。
注意,这里是ServerRequest,因为WebFlux中没有Servlet。
有了处理器,我们需要写一个Router来配置路由:
@Configuration
public class WelcomeRouter {
@Bean
public RouterFunction<ServerResponse> route(WelcomeHandler welcomeHandler) {
return RouterFunctions
.route(RequestPredicates.GET("/hello").
and(RequestPredicates.accept(MediaType.TEXT_PLAIN)), welcomeHandler::hello);
}
}
上面的代码将/hello和welcomeHandler::hello进行了绑定。
WelcomeWebClient和Application是和第一种方式是一样的。
public class WelcomeWebClient {
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();
}
}
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
WelcomeWebClient welcomeWebClient = new WelcomeWebClient();
log.info("react result is {}",welcomeWebClient.getResult());
}
}
Spring WebFlux的测试
怎么对webFlux代码进行测试呢?
本质上是和WelcomeWebClient的实现是一样的,我们去请求对应的对象,然后检测其返回值,最后判断返回值是否我们所期待的内容。
如下所示:
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class WelcomeRouterTest {
@Autowired
private WebTestClient webTestClient;
@Test
public void testHello() {
webTestClient
.get().uri("/hello")
.accept(MediaType.TEXT_PLAIN)
.exchange()
.expectStatus().isOk()
.expectBody(String.class).isEqualTo("www.flydean.com!");
}
}
总结
webFlux使用了Reactor作为底层的实现,和通常我们习惯的web请求方式是有很大不同的,但是通过我们的Spring框架,可以尽量保证原有的代码编写风格和习惯。
只需要在个别部分做微调。希望大家能够通过这个简单的例子,熟悉Reactive的基本编码实现。
本文的例子可以参考:springboot-reactive-web
本文作者:flydean程序那些事
本文链接:http://www.flydean.com/springboot-reactive-web/
本文来源:flydean的博客
欢迎关注我的公众号:「程序那些事」最通俗的解读,最深刻的干货,最简洁的教程,众多你不知道的小技巧等你来发现!
SpringBoot中的响应式web应用的更多相关文章
- (转)Spring Boot 2 (十):Spring Boot 中的响应式编程和 WebFlux 入门
http://www.ityouknow.com/springboot/2019/02/12/spring-boot-webflux.html Spring 5.0 中发布了重量级组件 Webflux ...
- SpringBoot使用WebFlux响应式编程操作数据库
这一篇文章介绍SpringBoot使用WebFlux响应式编程操作MongoDb数据库. 前言 在之前一篇简单介绍了WebFlux响应式编程的操作,我们在来看一下下图,可以看到,在目前的Spring ...
- springboot 使用webflux响应式开发教程(二)
本篇是对springboot 使用webflux响应式开发教程(一)的进一步学习. 分三个部分: 数据库操作webservicewebsocket 创建项目,artifactId = trading- ...
- 响应式WEB设计的9项基本原则
响 应式Web设计对于解决多类型屏幕问题来说是个不错方案,但从印刷的角度来看,其却存在着很多的困难.没有固定的页面尺寸.没有毫米或英寸,没有任何物理 限制,让人感到无从下手.随着建立网站可用的各种小工 ...
- 最佳的 14 个免费的响应式 Web 设计测试工具
一旦你决定要搭建一个网站就应该已经制定了设计标准.你认为下一步该做什么呢?测试!我使用“测试”这个词来检测你网站对不同屏幕和浏览器尺寸的响应情况.测试在响应式网页设计的过程中是很重要的一步.如果你明白 ...
- <HTML5和CSS3响应式WEB设计指南>译者序
"不是我不明白,这世界变化快."崔健的这首歌使用在互联网领域最合适不过.只短短数年的功夫,互联网的浪潮还没过去,移动互联网的时代已经来临.人们已经习惯将越来越多的时间花在各种移动设 ...
- 如何通过CSS3 实现响应式Web设计
如何通过CSS3 实现响应式Web设计: 分为三个步骤:(1)允许网页宽度自动调整.首先在页面头部中,我们需要加入这样一行:<meta name="viewport" con ...
- [转]响应式WEB设计学习(1)—判断屏幕尺寸及百分比的使用
原文地址:http://www.jb51.net/web/70360.html 现在移动设备越来越普及,用户使用智能手机.pad上网页越来越普遍.但是传统的fix型的页面在移动终端上无法很好的显示.因 ...
- css014 响应式web设计
css014 响应式web设计 一. 响应式web设计基础知识 1.rwd的三大理念:a.用于布局的弹性网络, b.用于图片和视频的弹性媒体,c.为不同屏幕宽度创建的不同样式的css媒体查询. ...
随机推荐
- hasura的golang反向代理
概述 反向代理代码 对请求的处理 对返回值的处理 遇到的问题 概述 一直在寻找一个好用的 graphql 服务, 之前使用比较多的是 prisma, 但是 prisma1 很久不再维护了, 而 pri ...
- Thumbnailator处理图片
读取源图 of(String... files) of(File... files) of(InputStream... inputStreams) of(URL... urls) 输出文件 toFi ...
- windows 快速安装Python3.7.2
1.官方下载地址:https://www.python.org/downloads/release/python-372/ 其他地址:http://www.uzzf.com/soft/449550.h ...
- linux(centos8):安装配置consul集群(consul 1.8.4 | centos 8.2.2004)
一,什么是consul? 1,Consul 是 HashiCorp 公司推出的开源软件,用于实现分布式系统的服务发现与配置. Consul 是分布式的.高可用的. 可横向扩展的 2,官方网站: h ...
- C# Timer用法及实例讲解
摘自:http://www.cnblogs.com/xcsn/archive/2013/05/10/3070485.html 1.C# Timer用法及实例详解 http://developer.51 ...
- 51node1256 乘法匿元(扩展欧几里得)
#include<iostream> using namespace std; int gcd(int a,int b,int &x,int &y){ if (b==0){ ...
- Java Web核心组件之Servlet的使用介绍
Servlet是Java Servlet的简称,称为小程序或服务连接器,用Java编写的服务端程序,主要功能在于交互式地浏览和修改数据,生成动态的Web内容:Servlet运行于支持Java的应用服务 ...
- 10 个 Python 初学者必知编码小技巧
技巧 #1 字符串翻转 a = "codementor">>> print "Reverse is",a[::-1]翻转后的结果为 rotne ...
- Stream(三)
public class Test08 { /* * 二.中间的加工操作 * (1)filter(Predicate p):过滤 * (2)distinct():去重 * (3)limit(long ...
- Java nio Server端示例
public class ServerNio { public static void main(String[] args) throws IOException, InterruptedExcep ...