SpringBoot3中使用虛擬線程的完整步驟
1. 環(huán)境準(zhǔn)備
JDK 21+:確保安裝 JDK 21 或更高版本
Spring Boot 3.2+:最低要求(pom.xml 或 build.gradle)
<!-- Maven 依賴 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version> <!-- 或更高版本 -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
// Gradle 依賴
plugins {
id 'java'
id 'org.springframework.boot' version '3.2.0'
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
}
2. 配置虛擬線程
方式一:全局啟用虛擬線程(Tomcat/Jetty)
import org.springframework.boot.web.embedded.tomcat.TomcatProtocolHandlerCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.Executors;
@Configuration
public class VirtualThreadConfig {
// Tomcat 配置(默認(rèn)服務(wù)器)
@Bean
public TomcatProtocolHandlerCustomizer<?> protocolHandlerVirtualThreadExecutorCustomizer() {
return protocolHandler ->
protocolHandler.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
}
// Jetty 配置(如使用Jetty)
// @Bean
// public JettyVirtualThreadsCustomizer jettyVirtualThreadsCustomizer() {
// return new JettyVirtualThreadsCustomizer();
// }
}
方式二:異步任務(wù)使用虛擬線程
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
@EnableAsync
public class AsyncConfig {
@Bean(name = "virtualThreadExecutor")
public Executor virtualThreadExecutor() {
return Thread.ofVirtual().name("virtual-", 0).factory()::newThread;
}
}
使用異步方法:
@Service
public class AsyncService {
@Async("virtualThreadExecutor") // 指定執(zhí)行器
public CompletableFuture<String> asyncTask() {
// 模擬耗時(shí)I/O操作
return CompletableFuture.completedFuture("Virtual thread task completed");
}
}
3. 驗(yàn)證虛擬線程
測試控制器
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.CompletableFuture;
@RestController
public class TestController {
@GetMapping("/thread")
public String getThreadType() {
// 打印當(dāng)前線程信息
Thread thread = Thread.currentThread();
return """
Thread name: %s
Is virtual: %s
Platform thread: %s
""".formatted(
thread.getName(),
thread.isVirtual(),
thread.isVirtual() ? "N/A" : thread.toString()
);
}
@GetMapping("/sleep")
public CompletableFuture<String> sleep() throws InterruptedException {
Thread.sleep(1000); // 模擬I/O阻塞
return CompletableFuture.completedFuture(
"Done by: " + Thread.currentThread().getName()
);
}
}
4. 啟動(dòng)應(yīng)用
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
5. 測試驗(yàn)證
1.訪問 http://localhost:8080/thread 查看線程類型:
Thread name: virtual-0
Is virtual: true
Platform thread: N/A
2.并發(fā)測試(使用 ab 或 JMeter):
ab -n 1000 -c 200 http://localhost:8080/sleep
觀察低內(nèi)存占用和高吞吐量
6.關(guān)鍵注意事項(xiàng)
阻塞操作識(shí)別:
- 虛擬線程在 synchronized 塊或本地方法調(diào)用時(shí)會(huì)固定到平臺(tái)線程
- 使用 jcmd <PID> Thread.dump_to_file -format=json <file> 分析線程狀態(tài)
線程局部變量:
- 虛擬線程支持 ThreadLocal,但避免濫用(可能增加內(nèi)存壓力)
- 考慮使用 ScopedValue(Java 21+)
數(shù)據(jù)庫連接池:
// application.properties spring.datasource.hikari.thread-factory=java.util.concurrent.ThreadFactory
調(diào)試配置:
java -Djdk.tracePinnedThreads=full -jar your-app.jar
7.完整配置示例(Tomcat + HikariCP)
@Configuration
public class VirtualThreadGlobalConfig {
// Tomcat 虛擬線程執(zhí)行器
@Bean
TomcatProtocolHandlerCustomizer<?> tomcatVirtualThreads() {
return handler -> handler.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
}
// HikariCP 使用虛擬線程工廠
@Bean
@ConfigurationProperties("spring.datasource.hikari")
public HikariDataSource dataSource() {
return new HikariDataSource(new HikariConfig() {{
setThreadFactory(Thread.ofVirtual().factory());
}});
}
// 異步任務(wù)執(zhí)行器
@Bean
Executor virtualThreadExecutor() {
return Executors.newVirtualThreadPerTaskExecutor();
}
}
重要提示:虛擬線程最適合 I/O 密集型場景(如網(wǎng)絡(luò)請求、數(shù)據(jù)庫調(diào)用),對計(jì)算密集型任務(wù)提升有限。生產(chǎn)環(huán)境務(wù)必進(jìn)行壓力測試!
到此這篇關(guān)于SpringBoot3中使用虛擬線程的完整步驟的文章就介紹到這了,更多相關(guān)SpringBoot3使用虛擬線程內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Springcloud中的@RefreshScope的實(shí)現(xiàn)
@RefreshScope注解是Spring Cloud中的一個(gè)注解,它用來實(shí)現(xiàn)Bean中屬性的動(dòng)態(tài)刷新,本文就來介紹一下@RefreshScope注解的使用,感興趣的可以了解一下2024-06-06
Java Druid連接池與Apache的DBUtils使用教程
這篇文章主要介紹了Java Druid連接池與Apache的DBUtils使用方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-12-12
Java弱鍵集合WeakHashMap及ConcurrentCache原理詳解
這篇文章主要介紹了Java弱鍵集合WeakHashMap及ConcurrentCache原理詳解,基于哈希表的Map接口實(shí)現(xiàn),支持null鍵和值,但是WeakHashMap具有弱鍵,可用來實(shí)現(xiàn)緩存存儲(chǔ),在進(jìn)行GC的時(shí)候會(huì)自動(dòng)回收鍵值對,需要的朋友可以參考下2023-09-09
詳解mybatis中association和collection的column傳入多個(gè)參數(shù)問題
這篇文章主要介紹了詳解mybatis中association和collection的column傳入多個(gè)參數(shù)問題,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10
mybatis自定義參數(shù)類型轉(zhuǎn)換器數(shù)據(jù)庫字段加密脫敏
這篇文章主要為大家介紹了mybatis自定義參數(shù)類型轉(zhuǎn)換器數(shù)據(jù)庫字段加密脫敏,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
使用springmvc參數(shù)接收boolean類型參數(shù)的問題
這篇文章主要介紹了使用springmvc參數(shù)接收boolean類型參數(shù)的問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
Springboot整合Druid實(shí)現(xiàn)對訪問的監(jiān)控方式
這篇文章主要介紹了Springboot整合Druid實(shí)現(xiàn)對訪問的監(jiān)控方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05

