SpringBoot系列:基于SpringBoot2.0的WebFlux应用入门

2024-02-15 16:48

本文主要是介绍SpringBoot系列:基于SpringBoot2.0的WebFlux应用入门,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Spring WebFlux是在Spring框架5中引入的一种新的反应式Web框架。与Spring MVC不同,它不需要servlet API,完全异步和非阻塞,并通过Reactive Project实现Reactive Streams规范。

官网文档地址:

https://docs.spring.io/spring/docs/5.0.5.RELEASE/spring-framework-reference/web-reactive.html#webflux

1、创建一个SpringBoot2.0项目

Eclipse中创建Maven工程,也可以使用Spring Initializer创建,在Pom.xml中添加依赖:

注意:SpringBoot2.0仅支持JDK8.0以上,不支持JDK6、JDK7

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.sample</groupId><artifactId>sun-sample-springboot-webflux</artifactId><version>0.0.1-SNAPSHOT</version><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>2.0.1.RELEASE</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-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>

Spring-boot-starter-webflux 将 spring-webflux、netty 以及其他必须的依赖包引入到类路径中。

h2database 是h2内存数据库,用于快速测试

jpa 是ORM操作,快速编写CRUD

工程主函数代码如下:

package com.suncht.sample;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class WebfluxApplication {public static void main(String[] args) {SpringApplication.run(WebfluxApplication.class, args);}
}

application.properties属性文件配置如下:

server.port=8080spring.datasource.url=jdbc:h2:file:D\:/h2/h2test;AUTO_SERVER=TRUE;DB_CLOSE_DELAY=-1
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.use_sql_comments=true
spring.jpa.properties.hibernate.format_sql=truespring.h2.console.enabled=true
spring.h2.console.path=/console
spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false#logging.level.root=debug

2、创建 HttpServer 

package com.suncht.sample.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;import reactor.ipc.netty.http.server.HttpServer;/*** 配置HttpServer* 可以配置基于Netty、基于Tomcat、基于Jetty* @author suncht**/
@Configuration
public class HttpServerConfig {@Autowiredprivate Environment environment;@Beanpublic HttpServer httpServer(RouterFunction<?> routerFunction) {HttpHandler httpHandler = RouterFunctions.toHttpHandler(routerFunction);ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);HttpServer server = HttpServer.create("localhost", Integer.valueOf(environment.getProperty("server.port")));server.newHandler(adapter);return server;}
}

这个根据应用配置中指定的端口创建一个 Netty HttpServer 服务器。Spring 支持例如 Tomcat 或者 Undertow 等其他服务器。因为 Netty 本身是异步的和事件驱动的,因此它更适合用来运行 Reactive 应用。而 Tomcat 使用 Java NIO 来实现 Servlet 规范。Netty 的 NIO 实现专门针对异步、事件驱动和非堵塞应用进行了优化。

3、编写Http请求的业务逻辑

WebFlux 支持两种编程:

(1)使用@Controller这种基于注解的姿势, 与Sring MVC的姿势相同,最简单最简洁

(2)基于Java 8 Lambda的函数式编程风格,需要编写Handler和Router

第一方式:基于注解

package com.suncht.sample.controller;import java.util.List;
import java.util.Optional;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import com.suncht.sample.model.User;
import com.suncht.sample.service.UserRepository;/*** WebFlux的第一种方式: annotation-based(注解)* @author suncht**/
@RestController
@RequestMapping("/users")
public class UserRestController {@Autowiredprivate UserRepository userRepository;@GetMapping("/")public List<User> getAllUser() {return userRepository.findAll();}@GetMapping("/{id}")public User getUser(@PathVariable Long id) {Optional<User> user = userRepository.findById(id);return user.get();}@GetMapping("/add/{userName}/{age}")public Long getUser(@PathVariable("userName") String userName, @PathVariable("age") Integer age) {User user = new User();user.setUserName(userName);user.setAge(age);User result = userRepository.save(user);return result.getId();}}

第二种方式:基于函数

package com.suncht.sample.handler;import java.util.Optional;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;import com.suncht.sample.model.User;
import com.suncht.sample.service.UserRepository;import reactor.core.publisher.Mono;/*** UserHandler* 用户操作的业务逻辑* @author suncht**/
@Service
public class UserHandler {@Autowiredprivate UserRepository userRepository;public Mono<ServerResponse> handleGetUserById(ServerRequest request) {Long userId = Long.valueOf(request.pathVariable("id"));Optional<User> user = userRepository.findById(userId);return ServerResponse.ok().body(Mono.just(user.get()), User.class).switchIfEmpty(ServerResponse.notFound().build());}	
}

这是针对用户的handler,其实就是用户的业务逻辑操作而已。跟我们平时写的业务逻辑不同是:返回对象Mono和Flux。

关于Mono和Flux,请参考官网:https://docs.spring.io/spring/docs/5.0.5.RELEASE/spring-framework-reference/web-reactive.html#webflux-fn-handler-functions

package com.suncht.sample.route;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 com.suncht.sample.handler.UserHandler;/*** WebFlux的第二种方式: functional(java方法)* Router路由,其实就是用代码实现http请求路径,类似于Python Web框架django,手动编写路由代码* @author suncht**/
@Configuration
public class UserRouter {@Beanpublic RouterFunction<?> routerFunction(UserHandler userHandler) {return RouterFunctions.route(RequestPredicates.GET("/api/user/{id}").and(RequestPredicates.accept(MediaType.APPLICATION_JSON)), userHandler::handleGetUserById);}
}

这是用户http请求的路由规则,手动编写。较第一方法而言,比较麻烦。

4、测试

可以在浏览器中直接输入HTTP地址:http://127.0.0.1:8080/api/user/2 进行测试

也可以使用WebFlux中的WebClient测试,代码如下:

package com.suncht.sample.test;import java.util.List;import org.junit.Before;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;import com.suncht.sample.model.User;import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;public class WebTest {private WebClient client = null;@Beforepublic void init() {client = WebClient.create("http://127.0.0.1:8080/");}@Testpublic void testUserById() {Mono<User> result = client.get()// 请求方法,get,post....uri("users/{id}", "1")// 请求相对地址以及参数.accept(MediaType.APPLICATION_JSON).retrieve()// 请求类型.bodyToMono(User.class);// 返回类型User user = result.block();System.out.println(user);}@Testpublic void testUserById2() {Mono<User> result2 = client.get()// 请求方法,get,post....uri("api/user/{id}", "1")// 请求相对地址以及参数.accept(MediaType.APPLICATION_JSON).retrieve()// 请求类型.bodyToMono(User.class);// 返回类型User user2 = result2.block();System.out.println(user2);}@Testpublic void testAllUsers() {Flux<User> userFlux = client.get().uri("users/").accept(MediaType.APPLICATION_JSON).retrieve()// 请求类型.bodyToFlux(User.class);// 返回类型List<User> users = userFlux.collectList().block();System.out.println(users);}}

WebClient是远程调用Http请求的一种工具类、新思路

5、其他代码

User实体:

package com.suncht.sample.model;import java.io.Serializable;import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;@Entity
@Table(name = "t_user")
public class User implements Serializable {private static final long serialVersionUID = 1L;@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;@Column(name="user_name", nullable=false, length=50)private String userName;@Column(name="age")private Integer age;public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}@Overridepublic String toString() {return "User [id=" + id + ", userName=" + userName + ", age=" + age + "]";}}

针对User的JPA CRUD操作:

package com.suncht.sample.service;import org.springframework.data.jpa.repository.JpaRepository;import com.suncht.sample.model.User;public interface UserRepository extends JpaRepository<User, Long> {
}

6、整个工程项目结构预览


GitHub代码: https://github.com/suncht/sun-test/tree/master/springboot2.webflux.test

这篇关于SpringBoot系列:基于SpringBoot2.0的WebFlux应用入门的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/711954

相关文章

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

SpringBoot+Docker+Graylog 如何让错误自动报警

《SpringBoot+Docker+Graylog如何让错误自动报警》SpringBoot默认使用SLF4J与Logback,支持多日志级别和配置方式,可输出到控制台、文件及远程服务器,集成ELK... 目录01 Spring Boot 默认日志框架解析02 Spring Boot 日志级别详解03 Sp

java中反射Reflection的4个作用详解

《java中反射Reflection的4个作用详解》反射Reflection是Java等编程语言中的一个重要特性,它允许程序在运行时进行自我检查和对内部成员(如字段、方法、类等)的操作,本文将详细介绍... 目录作用1、在运行时判断任意一个对象所属的类作用2、在运行时构造任意一个类的对象作用3、在运行时判断

java如何解压zip压缩包

《java如何解压zip压缩包》:本文主要介绍java如何解压zip压缩包问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java解压zip压缩包实例代码结果如下总结java解压zip压缩包坐在旁边的小伙伴问我怎么用 java 将服务器上的压缩文件解压出来,

PostgreSQL的扩展dict_int应用案例解析

《PostgreSQL的扩展dict_int应用案例解析》dict_int扩展为PostgreSQL提供了专业的整数文本处理能力,特别适合需要精确处理数字内容的搜索场景,本文给大家介绍PostgreS... 目录PostgreSQL的扩展dict_int一、扩展概述二、核心功能三、安装与启用四、字典配置方法

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Spring WebFlux 与 WebClient 使用指南及最佳实践

《SpringWebFlux与WebClient使用指南及最佳实践》WebClient是SpringWebFlux模块提供的非阻塞、响应式HTTP客户端,基于ProjectReactor实现,... 目录Spring WebFlux 与 WebClient 使用指南1. WebClient 概述2. 核心依

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

从入门到精通MySQL联合查询

《从入门到精通MySQL联合查询》:本文主要介绍从入门到精通MySQL联合查询,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下... 目录摘要1. 多表联合查询时mysql内部原理2. 内连接3. 外连接4. 自连接5. 子查询6. 合并查询7. 插入查询结果摘要前面我们学习了数据库设计时要满