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

相关文章

springboot集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

SpringBoot中@Value注入静态变量方式

《SpringBoot中@Value注入静态变量方式》SpringBoot中静态变量无法直接用@Value注入,需通过setter方法,@Value(${})从属性文件获取值,@Value(#{})用... 目录项目场景解决方案注解说明1、@Value("${}")使用示例2、@Value("#{}"php

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。

java.sql.SQLTransientConnectionException连接超时异常原因及解决方案

《java.sql.SQLTransientConnectionException连接超时异常原因及解决方案》:本文主要介绍java.sql.SQLTransientConnectionExcep... 目录一、引言二、异常信息分析三、可能的原因3.1 连接池配置不合理3.2 数据库负载过高3.3 连接泄漏