当前位置: 代码网 > it编程>编程语言>Java > SpringBoot3中使用虚拟线程的完整步骤

SpringBoot3中使用虚拟线程的完整步骤

2025年06月08日 Java 我要评论
1. 环境准备jdk 21+:确保安装 jdk 21 或更高版本spring boot 3.2+:最低要求(pom.xml 或 build.gradle)<!-- maven 依赖 -->

1. 环境准备

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 配置(默认服务器)
    @bean
    public tomcatprotocolhandlercustomizer<?> protocolhandlervirtualthreadexecutorcustomizer() {
        return protocolhandler -> 
            protocolhandler.setexecutor(executors.newvirtualthreadpertaskexecutor());
    }

    // jetty 配置(如使用jetty)
    // @bean
    // public jettyvirtualthreadscustomizer jettyvirtualthreadscustomizer() {
    //    return new jettyvirtualthreadscustomizer();
    // }
}

方式二:异步任务使用虚拟线程

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")  // 指定执行器
    public completablefuture<string> asynctask() {
        // 模拟耗时i/o操作
        return completablefuture.completedfuture("virtual thread task completed");
    }
}

3. 验证虚拟线程

测试控制器

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() {
        // 打印当前线程信息
        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. 启动应用

@springbootapplication
public class application {
    public static void main(string[] args) {
        springapplication.run(application.class, args);
    }
}

5. 测试验证

1.访问 http://localhost:8080/thread 查看线程类型:

thread name: virtual-0
is virtual: true
platform thread: n/a

2.并发测试(使用 ab 或 jmeter):

ab -n 1000 -c 200 http://localhost:8080/sleep

观察低内存占用和高吞吐量

6.关键注意事项

阻塞操作识别:

  • 虚拟线程在 synchronized 块或本地方法调用时会固定到平台线程
  • 使用 jcmd <pid> thread.dump_to_file -format=json <file> 分析线程状态

线程局部变量:

  • 虚拟线程支持 threadlocal,但避免滥用(可能增加内存压力)
  • 考虑使用 scopedvalue(java 21+)

数据库连接池:

// application.properties
spring.datasource.hikari.thread-factory=java.util.concurrent.threadfactory

调试配置:

java -djdk.tracepinnedthreads=full -jar your-app.jar

7.完整配置示例(tomcat + hikaricp)

@configuration
public class virtualthreadglobalconfig {

    // tomcat 虚拟线程执行器
    @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());
        }});
    }

    // 异步任务执行器
    @bean
    executor virtualthreadexecutor() {
        return executors.newvirtualthreadpertaskexecutor();
    }
}

重要提示:虚拟线程最适合 i/o 密集型场景(如网络请求、数据库调用),对计算密集型任务提升有限。生产环境务必进行压力测试!

到此这篇关于springboot3中使用虚拟线程的完整步骤的文章就介绍到这了,更多相关springboot3使用虚拟线程内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com