WebFlux基于Netty,其異步復(fù)用線程模型與非阻塞IO帶來(lái)的優(yōu)勢(shì)相比SpringMVC/Tomcat技術(shù)棧筷凤,可以帶來(lái)更小的線程切換開(kāi)銷,更重要的是可以避免應(yīng)用間的級(jí)聯(lián)故障。對(duì)于Tomcat模型經(jīng)常需要考慮的問(wèn)題是線程池的參數(shù)調(diào)優(yōu)悼凑,以及線程池隔離來(lái)做故障模塊的隔離熔斷摊聋。而異步非阻塞技術(shù)棧天然避免了這些問(wèn)題鸡捐。
以往由于JDBC是同步阻塞協(xié)議的原因,WebFlux技術(shù)棧一般應(yīng)用于純請(qǐng)求轉(zhuǎn)發(fā)類的場(chǎng)景麻裁,在涉及到關(guān)系型數(shù)據(jù)的場(chǎng)景受限箍镜。有了R2DBC之后則補(bǔ)上了這塊拼圖源祈。
使用的demo應(yīng)用代碼
搭建一個(gè)WebFlux應(yīng)用,包含/user/getAllUser/
和/user/slow/
兩個(gè)接口色迂,應(yīng)用使用r2dbc連接MySQL數(shù)據(jù)庫(kù)香缺,實(shí)現(xiàn)全鏈路異步非阻塞。
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wangan</groupId>
<artifactId>springbootone</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springbootone</name>
<description>springbootone</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.7.3</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-r2dbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>dev.miku</groupId>
<artifactId>r2dbc-mysql</artifactId>
<version>0.8.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.1.17.RELEASE</version>
<configuration>
<mainClass>com.wangan.springbootone.SpringbootoneApplication</mainClass>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
配置文件:
spring.application.name=springbootone
server.port=8080
spring.r2dbc.driver-class-name=com.mysql.jdbc.Driver
spring.r2dbc.username=root
spring.r2dbc.password=root
spring.r2dbc.url=r2dbc:pool:mysql://xxx.xx.xxx.187:3306/db_core?useSSL=false&useUnicode=true&characterEncoding=UTF8&autoReconnect=true
repository
public interface UserRepository extends ReactiveCrudRepository<User, Integer> {
@Query(value = "select sleep(10) ")
public Mono<User> slowQuery();
}
entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Table("webflux_user")
public class User {
@Id
private int id;
private String username;
private String password;
}
service
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public Mono<User> addUser(User user) {
return userRepository.save(user);
}
public Mono<ResponseEntity<Void>> delUser(int id) {
return userRepository.findById(id)
.flatMap(user -> userRepository.delete(user).then(Mono.just(new ResponseEntity<Void>(HttpStatus.OK))))
.defaultIfEmpty(new ResponseEntity<Void>(HttpStatus.NOT_FOUND));
}
public Mono<ResponseEntity<User>> updateUser(User user) {
return userRepository.findById(user.getId())
.flatMap(user0 -> userRepository.save(user))
.map(user0 -> new ResponseEntity<User>(user0, HttpStatus.OK))
.defaultIfEmpty(new ResponseEntity<User>(HttpStatus.NOT_FOUND));
}
public Flux<User> getAllUser() {
return userRepository.findAll();
}
public Mono<ResponseEntity<User>> slowFunction(){
return userRepository.slowQuery()
//.flatMap(user0 -> userRepository.save(user))
.map(user0 -> new ResponseEntity<User>(user0, HttpStatus.OK))
.defaultIfEmpty(new ResponseEntity<User>(HttpStatus.NOT_FOUND));
}
}
controller
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "getAllUser", method = RequestMethod.GET)
public Flux<User> getAllUser() {
return userService.getAllUser();
}
@RequestMapping(value = "slow", method = RequestMethod.GET)
public Mono<ResponseEntity<User>> slow() {
return userService.slowFunction();
}
}
異步非阻塞能力測(cè)試
為了實(shí)驗(yàn)方便歇僧,先把webflux的工作線程設(shè)置為1:
@Configuration
public class ReactNettyConfiguration {
@Bean
public ReactorResourceFactory reactorClientResourceFactory() {
System.setProperty("reactor.netty.ioSelectCount","1");
// 這里工作線程數(shù)為2-4倍都可以图张。看具體情況
//int ioWorkerCount = Math.max(Runtime.getRuntime().availableProcessors()*3, 4));
System.setProperty("reactor.netty.ioWorkerCount",String.valueOf(1));
return new ReactorResourceFactory();
}
}
此時(shí)應(yīng)用內(nèi)的線程情況诈悍,只有一個(gè)工作線程來(lái)處理請(qǐng)求:
兩個(gè)接口
localhost:8080/user/getAllUser/
先調(diào)用slow接口(用select sleep(10)模擬的由慢SQL導(dǎo)致的慢接口)祸轮,再調(diào)用getAllUser,后者可以馬上返回侥钳。同樣的測(cè)試案例和配置适袜,如果使用SpringMVC + JDBC的組合就會(huì)發(fā)生slow接口10秒后返回,此時(shí)getAllUser才可以返回舷夺。
后續(xù)
- 關(guān)于遠(yuǎn)程調(diào)用的異步非阻塞:上述應(yīng)用中使用r2dbc調(diào)用MySQL苦酱,如果該應(yīng)用需要調(diào)用遠(yuǎn)程的Http服務(wù),則需要使用
WebClient
替代RestTemplate
冕房、Apache HttpClient
之類的傳統(tǒng)Http客戶端組件躏啰,實(shí)現(xiàn)全鏈路異步非阻塞。如果是該應(yīng)用需要調(diào)用的后端服務(wù)是Dubbo服務(wù)耙册,理論上只要將Dubbo客戶端調(diào)用結(jié)果轉(zhuǎn)為Reactive Streams返回仍然可以實(shí)現(xiàn)上述非阻塞調(diào)用效果给僵。 - (未完成)上述例子中,我們利用新的連接驅(qū)動(dòng)r2dbc代替了jdbc详拙,實(shí)現(xiàn)了異步非阻塞的與數(shù)據(jù)庫(kù)網(wǎng)絡(luò)通信帝际,然后這里其實(shí)也可以使用個(gè)連接池,見(jiàn):Data Access with R2DBC :: Spring Framework “When you use Spring’s R2DBC layer, you can configure your own with a connection pool implementation provided by a third party. A popular implementation is R2DBC Pool (). Implementations in the Spring distribution are meant only for testing purposes and do not provide pooling.”
參考
https://docs.spring.io/spring-framework/reference/data-access/r2dbc.html
SpringBoot之Webflux&R2DBC操作MySQL
Spring Cloud Gateway 雪崩了饶辙,我 TM 人傻了 - 知乎 (zhihu.com)
https://blog.csdn.net/weixin_42182797/article/details/117216371