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. 啟動應(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)
阻塞操作識別:
- 虛擬線程在 synchronized 塊或本地方法調(diào)用時(shí)會固定到平臺線程
- 使用 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)文章
RestTemplate Get請求實(shí)現(xiàn)bean參數(shù)傳遞詳解
RestTemplate 是從 Spring3.0 開始支持的一個(gè) HTTP 請求工具,也有的稱之為網(wǎng)絡(luò)框架,說白了就是Java版本的一個(gè)postman,這篇文章主要介紹了詳解RestTemplate 用法,需要的朋友可以參考下2022-11-11springboot整合mybatis中的問題及出現(xiàn)的一些問題小結(jié)
這篇文章主要介紹了springboot整合mybatis中的問題及出現(xiàn)的一些問題小結(jié),本文給出了解決方案,需要的朋友可以參考下2018-11-11Spring+Quartz配置定時(shí)任務(wù)實(shí)現(xiàn)代碼
這篇文章主要介紹了Spring+Quartz配置定時(shí)任務(wù)實(shí)現(xiàn)代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04