Spring-webflux

Spring 5.0 Spring-webflux 是一个全新的非堵塞的函数式 Reactive Web 框架,可以用来构建异步的、非堵塞的、事件驱动的服务。

springboot2.0发布不久,最近研究了一下springboot2.0的新特性,其中就发现了webflux。

下面是spring-flux的一个demo话不多少上代码

使用webflux和MVC的区别就是在artifacId后面加上flux

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "hello world";
}
}

在webflux中有Handler和Router 的概念,分别与springmvc中的controllerr和equest mapper相对应,通俗的将就是handler就是真正处理请求的bean,可以在handler中编写处理请求的逻辑,而Router就是如何让请求找到对应的handler中的方法处理,下面我们来实现一个简单的handler和router。

@Component
public class HelloWorldHandler { public Mono<ServerResponse> helloWorld(ServerRequest request){
return ServerResponse.ok()
.contentType(MediaType.TEXT_PLAIN)
.body(BodyInserters.fromObject("hello flux"));
} }

上面是一个简单的handler只相应了一个“hello flux” 字符串!

@Configuration
public class RouterConfig { @Autowired
private HelloWorldHandler helloWorldHandler; @Bean
public RouterFunction<?> helloRouter() {
return RouterFunctions.route(RequestPredicates.GET("/hello"), helloWorldHandler::helloWorld);
} }

上面是对应的router对应的是匹配一个get方式的/hello请求,然后调用helloWorldHandler中的helloWorld方法向浏览器输出一个文本类型的字符串

再来一个例子

@Component
public class UserHandler { @Autowired
private ReactiveRedisConnection connection; public Mono<ServerResponse> getTime(ServerRequest request) {
return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN)
.body(Mono.just("Now is " + new SimpleDateFormat("HH:mm:ss").format(new Date())), String.class);
}
public Mono<ServerResponse> getDate(ServerRequest request) {
return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN)
.body(Mono.just("Today is " + new SimpleDateFormat("yyyy-MM-dd").format(new Date())), String.class);
} public Mono<ServerResponse> sendTimePerSec(ServerRequest request) {
return ServerResponse.ok().contentType(MediaType.TEXT_EVENT_STREAM)
.body(Flux.interval(Duration.ofSeconds(1)).map(l -> new SimpleDateFormat("HH:mm:ss").format(new Date())), String.class);
} public Mono<ServerResponse> register(ServerRequest request) {
Mono<Map> body = request.bodyToMono(Map.class);
return body.flatMap(map -> {
String username = (String) map.get("username");
String password = (String) map.get("password");
String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt());
return connection.stringCommands()
.set(ByteBuffer.wrap(username.getBytes()), ByteBuffer.wrap(hashedPassword.getBytes()));
}).flatMap(aBoolean -> {
Map<String, String> result = new HashMap<>();
ServerResponse serverResponse = null;
if (aBoolean){
result.put("message", "successful");
return ServerResponse.ok()
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(BodyInserters.fromObject(result));
}else {
result.put("message", "failed");
return ServerResponse.status(HttpStatus.BAD_REQUEST)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(BodyInserters.fromObject(request));
}
}); } public Mono<ServerResponse> login(ServerRequest request) {
Mono<Map> body = request.bodyToMono(Map.class);
return body.flatMap(map -> {
String username = (String) map.get("username");
String password = (String) map.get("password");
return connection.stringCommands().get(ByteBuffer.wrap(username.getBytes())).flatMap(byteBuffer -> {
byte[] bytes = new byte[byteBuffer.remaining()];
byteBuffer.get(bytes, 0, bytes.length);
String hashedPassword = null;
try {
hashedPassword = new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Map<String, String> result = new HashMap<>();
if (hashedPassword == null || !BCrypt.checkpw(password, hashedPassword)) {
result.put("message", "账号或密码错误");
return ServerResponse.status(HttpStatus.UNAUTHORIZED)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(BodyInserters.fromObject(result));
} else {
result.put("token", "无效token");
return ServerResponse.ok()
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(BodyInserters.fromObject(result));
}
});
});
} }

@Configuration
public class RouterConfig { @Autowired
private HelloWorldHandler helloWorldHandler; @Bean
public RouterFunction<?> helloRouter() {
return RouterFunctions.route(RequestPredicates.GET("/hello"), helloWorldHandler::helloWorld);
} @Autowired
private UserHandler userHandler; @Bean
public RouterFunction<ServerResponse> timerRouter() {
return RouterFunctions.route(RequestPredicates.GET("/time"), userHandler::getTime)
.andRoute(RequestPredicates.GET("/date"), userHandler::getDate);
} @Bean
public RouterFunction<?> routerFunction() {
return RouterFunctions.route(RequestPredicates.GET("/hello"), helloWorldHandler::helloWorld)
.andRoute(RequestPredicates.POST("/register"), userHandler::register)
.andRoute(RequestPredicates.POST("/login"), userHandler::login)
.andRoute(RequestPredicates.GET("/times"), userHandler::sendTimePerSec);
} }

Spring webflux的更多相关文章

  1. Spring Webflux: Kotlin DSL [片断]

    原文链接:https://dzone.com/articles/spring-webflux-kotlin-dsl-snippets 作者:Biju Kunjummen 译者:Jackie Tang ...

  2. Spring WebFlux开门迎客,却来了一位特殊客人

    话说Spring WebFlux已经出现有一段时间了,但是知道他的人并不是很多.这让他很是闷闷不乐. 还有更惨的是,那些敢于吃螃蟹的人在尝试了他之后,有的竟把代码重新改回到Spring MVC的同步模 ...

  3. 爸爸又给Spring MVC生了个弟弟叫Spring WebFlux

    情景引入 很早之前,Java就火起来了,是因为它善于开发和处理网络方面的应用. Java有一个爱好,就是喜欢制定规范标准,但自己又不善于去实现. 反倒是一些服务提供商使用它的规范标准来制造应用服务器而 ...

  4. Spring WebFlux 响应式编程学习笔记(一)

    各位Javaer们,大家都在用SpringMVC吧?当我们不亦乐乎的用着SpringMVC框架的时候,Spring5.x又悄(da)无(zhang)声(qi)息(gu)的推出了Spring WebFl ...

  5. Spring WebFlux 要革了谁的命?

    Spring WebFlux 要革了谁的命?  mp.weixin.qq.com 托梦 Java国王昨晚做了一个梦. 梦中有个白胡子老头儿,颇有仙风道骨, 告诉他说:“你们Java啊,实在是太弱了,连 ...

  6. 基于Angular和Spring WebFlux做个小Demo

    前言 随着Spring Boot2.0正式发布,Spring WebFlux正式来到了Spring Boot大家族里面.由于Spring WebFlux可以通过更少的线程去实现更高的并发和使用更少的硬 ...

  7. Spring WebFlux, 它是一种异步的, 非阻塞的, 支持背压(Back pressure)机制的Web 开发WebFlux 支持两种编程风(姿)格(势) 使用@Controller这种基于注解

    概述 什么是 Spring WebFlux, 它是一种异步的, 非阻塞的, 支持背压(Back pressure)机制的Web 开发框架. 要深入了解 Spring WebFlux, 首先要了知道 R ...

  8. 朱晔和你聊Spring系列S1E5:Spring WebFlux小探

    阅读PDF版本 本文会来做一些应用对比Spring MVC和Spring WebFlux,观察线程模型的区别,然后做一下简单的压力测试. 创建一个传统的Spring MVC应用 先来创建一个新的web ...

  9. 【SFA官方翻译】Spring WebFlux和Spring Cloud进行响应式微服务开发

    源码,修正一些错误: https://github.com/bigben0123/sample-spring-cloud-webflux 原创 SpringForAll社区 2018-05-18 作者 ...

  10. 初识Spring Webflux

    Important to know is that there are two ways to use Spring Webflux. One using annotations, which is ...

随机推荐

  1. ubuntu Pycharm 2017 3.3 Active

    1.打开激活窗口 2.选择 Activate new license with License server (用license server 激活) 3.在 License sever addres ...

  2. C语言面试题分类->链表

    链表的创建,清空,插入,删除 typedef int (* __compfunc)(const void *, const void *); //Traverse list. Fast macro t ...

  3. ndk编译faac生成库

    1.编译脚本如下: NDK=/opt/android-ndk-r9d TOOLCHAIN=$NDK/toolchains/arm-linux-androideabi-4.6/prebuilt/linu ...

  4. JSP的执行原理

    在一个JSP文件第一次被请求时,JSP引擎把该JSP文件转换成为一个Servlet.而这个引擎本身也是一个Servlet.JSP的运行过程如下所示: (1)JSP引擎先把该JSP文件转换成一个Java ...

  5. docker 及 docker-compose 的快速安装和简单使用

    本篇将使用 DaoCloud 源在 Ubuntu 上简单快速安装 docker 及 docker-compose 并添加了通过 Dockerfile 及 docker-compose.yml 使用 n ...

  6. [Swift]LeetCode304. 二维区域和检索 - 矩阵不可变 | Range Sum Query 2D - Immutable

    Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...

  7. [Swift]LeetCode717. 1比特与2比特字符 | 1-bit and 2-bit Characters

    We have two special characters. The first character can be represented by one bit 0. The second char ...

  8. docker 常用命令记录

    下载镜像 docker pull imagesName 查看所有镜像 docker images 查看当前运行的镜像 docker ps 运行镜像 docker run imagesName 停止运行 ...

  9. Jenkins时区设置为北京时间

    打开 [系统管理]->[脚本命令行]运行下面的命令 System.setProperty('org.apache.commons.jelly.tags.fmt.timeZone', 'Asia/ ...

  10. C#版 - Leetcode 633. 平方数之和 - 题解

    版权声明: 本文为博主Bravo Yeung(知乎UserName同名)的原创文章,欲转载请先私信获博主允许,转载时请附上网址 http://blog.csdn.net/lzuacm. C#版 - L ...