Spring Boot 3.x虚拟线程(Virtual Thread)集成配置问题详解与解决方案

【Java虚拟线程】Java21、SpringBoot3中使用虚拟线程 最近有读取文件中数据的需求,且数据量百万至千万,普通的多线程读取方式还是很慢。遂想到Java21中虚拟线程,在网上学习了一圈,简单的在这里记一个笔记,方便日后查找。 阅读详情

Spring Boot 3.x虚拟线程(Virtual Thread)集成配置问题详解与解决方案

一、问题背景与概述

1.1 虚拟线程简介

Java 19引入的虚拟线程(Virtual Threads)是轻量级线程,由JVM管理而非操作系统:

// 传统平台线程
Thread platformThread = new Thread(() -> {
    System.out.println("Platform thread: " + Thread.currentThread());
});

// 虚拟线程
Thread virtualThread = Thread.startVirtualThread(() -> {
    System.out.println("Virtual thread: " + Thread.currentThread());
});

1.2 Spring Boot 3.x集成问题

主要问题表现:

  1. Tomcat/Jetty容器配置问题
  2. 数据库连接池不兼容
  3. ThreadLocal/InheritableThreadLocal失效
  4. MDC日志上下文丢失
  5. 事务管理异常
  6. Reactive与虚拟线程冲突
  7. 监控和调试困难

二、Web容器虚拟线程配置问题

2.1 Tomcat虚拟线程配置

问题现象:

# application.yml - 错误配置示例
server:
  tomcat:
    threads:
      max: 200
      min-spare: 10
  # 虚拟线程配置缺失

错误信息:

WARNING: Virtual threads not enabled for Tomcat
解决方案:
// 方案1:通过配置类启用Tomcat虚拟线程
@Configuration
public class TomcatVirtualThreadConfig {
    
    @Bean
    public TomcatProtocolHandlerCustomizer<?> protocolHandlerVirtualThreadCustomizer() {
        return protocolHandler -> {
            // 关键配置:使用虚拟线程执行器
            protocolHandler.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
            
            // 优化虚拟线程池配置
            if (protocolHandler instanceof AbstractHttp11Protocol<?> http11) {
                // 调整连接器参数
                http11.setMaxConnections(10000);  // 提高最大连接数
                http11.setMaxThreads(1000);       // 虚拟线程下可设置更高
                http11.setConnectionTimeout(30000);
                http11.setKeepAliveTimeout(60000);
                http11.setMaxKeepAliveRequests(100);
            }
        };
    }
    
    @Bean
    public WebServerFactoryCustomizer<TomcatServletWebServerFactory> tomcatCustomizer() {
        return factory -> {
            factory.addConnectorCustomizers(connector -> {
                // 设置连接器属性
                connector.setProperty("maxThreads", "1000");
                connector.setProperty("acceptorThreadCount", "2");
                connector.setProperty("minSpareThreads", "5");
                
                // 启用虚拟线程特性
                connector.setProperty("useVirtualThreads", "true");
                connector.setProperty("virtualThreadKeepAlive", "60");
            });
            
            // 优化Tomcat配置
            factory.addContextCustomizers(context -> {
                context.setSessionTimeout(30);
                context.setBackgroundProcessorDelay(10);
            });
        };
    }
}

// 方案2:完整的Tomcat虚拟线程工厂配置
@Configuration
@ConditionalOnWebApplication(type = Type.SERVLET)
public class FullTomcatVirtualThreadConfig {
    
    @Value("${server.tomcat.virtual-threads.max-pool-size:1000}")
    private int maxPoolSize;
    
    @Value("${server.tomcat.virtual-threads.keep-alive-seconds:60}")
    private int keepAliveSeconds;
    
    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
        
        factory.addConnectorCustomizers(connector -> {
            ProtocolHandler handler = connector.getProtocolHandler();
            
            if (handler instanceof AbstractHttp11Protocol<?> http11) {
                // 虚拟线程专用配置
                configureForVirtualThreads(http11);
            }
        });
        
        return factory;
    }
    
    private void configureForVirtualThreads(AbstractHttp11Protocol<?> protocol) {
        // 创建虚拟线程执行器
        ExecutorService virtualThreadExecutor = createVirtualThreadExecutor();
        protocol.setExecutor(virtualThreadExecutor);
        
        // 优化协议参数
        protocol.setMaxConnections(10000);
        protocol.setConnectionTimeout(30000);
        protocol.setConnectionUploadTimeout(60000);
        protocol.setDisableUploadTimeout(false);
        protocol.setKeepAliveTimeout(60000);
        protocol.setMaxKeepAliveRequests(100);
        protocol.setMaxSwallowSize(2097152); // 2MB
        protocol.setUseSendfile(true);
        
        // SSL优化
        protocol.setSSLEnabled(true);
        protocol.setSSLProtocol("TLSv1.2+TLSv1.3");
        protocol.setUseServerCipherSuitesOrder(true);
        
        // 压缩配置
        protocol.setCompression("on");
        protocol.setCompressionMinSize(2048);
        protocol.setCompressableMimeType(
            "text/html,text/xml,text/plain,text/css,text/javascript," +
            "application/javascript,application/json,application/xml");
    }
    
    private ExecutorService createVirtualThreadExecutor() {
        ThreadFactory virtualThreadFactory = Thread.ofVirtual()
            .name("tomcat-virtual-", 0)
            .factory();
        
        // 使用虚拟线程工厂
        return Executors.newThreadPerTaskExecutor(virtualThreadFactory);
    }
}

// 方案3:YAML配置配合代码
# application.yml
server:
  port: 8080
  tomcat:
    virtual-threads:
      enabled: true
      max-pool-size: 1000
      keep-alive-seconds: 60
      thread-name-prefix: "tomcat-vt-"
    connection-timeout: 30s
    max-connections: 10000
    keep-alive:
      timeout: 60s
      max-requests: 100
    compression:
      enabled: true
      min-response-size: 2KB
      mime-types: 
        - text/html
        - text/xml
        - text/plain
        - text/css
        - application/json
    accesslog:
      enabled: true
      pattern: "%t %a %r %s %D %{User-Agent}i"

2.2 Jetty虚拟线程配置

@Configuration
@ConditionalOnClass(org.eclipse.jetty.server.Server.class)
public class JettyVirtualThreadConfig {
    
    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
        JettyServletWebServerFactory factory = new JettyServletWebServerFactory();
        
        factory.addServerCustomizers(server -> {
            // 配置Jetty使用虚拟线程
            QueuedThreadPool threadPool = new QueuedThreadPool();
            threadPool.setVirtualThreadsExecutor(Executors.newVirtualThreadPerTaskExecutor());
            threadPool.setMaxThreads(1000);
            threadPool.setMinThreads(10);
            threadPool.setIdleTimeout(60000);
            
            server.setThreadPool(threadPool);
            
            // 优化连接器
            for (Connector connector : server.getConnectors()) {
                if (connector instanceof ServerConnector serverConnector) {
                    configureJettyConnector(serverConnector);
                }
            }
        });
        
        return factory;
    }
    
    private void configureJettyConnector(ServerConnector connector) {
        HttpConfiguration httpConfig = connector.getConnectionFactory(
            HttpConnectionFactory.class).getHttpConfiguration();
        
        // 优化HTTP配置
        httpConfig.setRequestHeaderSize(8192);
        httpConfig.setResponseHeaderSize(8192);
        httpConfig.setSendServerVersion(false);
        httpConfig.setSendDateHeader(true);
        httpConfig.setHeaderCacheSize(512);
        
        // 连接器参数
        connector.setAcceptQueueSize(1024);
        connector.setIdleTimeout(30000);
        
        // SSL配置
        SslConnectionFactory sslConnFactory = connector.getConnectionFactory(
            SslConnectionFactory.class);
        if (sslConnFactory != null) {
            SslContextFactory.Server sslContextFactory = 
                (SslContextFactory.Server) sslConnFactory.getSslContextFactory();
            sslContextFactory.setExcludeCipherSuites(
                "SSL_RSA_WITH_DES_CBC_SHA",
                "SSL_DHE_RSA_WITH_DES_CBC_SHA",
                "SSL_DHE_DSS_WITH_DES_CBC_SHA"
            );
        }
    }
}

三、数据库连接池问题

3.1 HikariCP虚拟线程兼容性问题

问题现象:

WARNING: HikariPool-1 - Connection is not available, request timed out after 30000ms.
解决方案:
// 方案1:优化HikariCP配置
@Configuration
public class HikariVirtualThreadConfig {
    
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.hikari")
    public HikariDataSource dataSource(DataSourceProperties properties) {
        HikariConfig config = new HikariConfig();
        
        // 虚拟线程优化配置
        config.setJdbcUrl(properties.getUrl());
        config.setUsername(properties.getUsername());
        config.setPassword(properties.getPassword());
        config.setDriverClassName(properties.getDriverClassName());
        
        // 关键:调整连接池参数适应虚拟线程
        config.setMaximumPoolSize(100);           // 虚拟线程下可减少
        config.setMinimumIdle(10);                // 最小空闲连接
        config.setConnectionTimeout(30000);       // 连接超时
        config.setIdleTimeout(600000);           // 空闲超时10分钟
        config.setMaxLifetime(1800000);          // 最大生命周期30分钟
        config.setKeepaliveTime(30000);          // 保活时间
        
        // 虚拟线程专用优化
        config.addDataSourceProperty("useVirtualThreads", "true");
        config.addDataSourceProperty("prepStmtCacheSize", 250);
        config.addDataSourceProperty("prepStmtCacheSqlLimit", 2048);
        config.addDataSourceProperty("cachePrepStmts", true);
        config.addDataSourceProperty("useServerPrepStmts", true);
        
        // 监控相关
        config.setMetricRegistry(null);  // 虚拟线程下可能不需要
        config.setHealthCheckRegistry(null);
        
        // 泄漏检测
        config.setLeakDetectionThreshold(60000);
        
        return new HikariDataSource(config);
    }
}

// 方案2:使用虚拟线程感知的连接池包装器
@Component
public class VirtualThreadAwareDataSource implements DataSource {
    
    private final DataSource delegate;
    private final ExecutorService virtualThreadExecutor;
    
    public VirtualThreadAwareDataSource(DataSource delegate) {
        this.delegate = delegate;
        this.virtualThreadExecutor = Executors.newVirtualThreadPerTaskExecutor();
    }
    
    @Override
    public Connection getConnection() throws SQLException {
        // 在虚拟线程中获取连接
        try {
            return virtualThreadExecutor.submit(delegate::getConnection).get();
        } catch (InterruptedException | ExecutionException e) {
            throw new SQLException("Failed to get connection in virtual thread", e);
        }
    }
    
    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        // 类似实现
        return delegate.getConnection(username, password);
    }
    
    // 其他DataSource方法实现...
    
    @PreDestroy
    public void shutdown() {
        virtualThreadExecutor.shutdown();
    }
}

// 方案3:配置属性文件
# application.yml
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/db?useSSL=false&serverTimezone=UTC
    username: root
    password: password
    driver-class-name: com.mysql.cj.jdbc.Driver
    hikari:
      maximum-pool-size: 50                # 虚拟线程下可以减少
      minimum-idle: 5
      connection-timeout: 30000
      idle-timeout: 600000
      max-lifetime: 1800000
      pool-name: VirtualThreadPool
      leak-detection-threshold: 60000
      connection-test-query: SELECT 1
      data-source-properties:
        useVirtualThreads: true
        cachePrepStmts: true
        prepStmtCacheSize: 250
        prepStmtCacheSqlLimit: 2048
        useServerPrepStmts: true
        useLocalSessionState: true
        rewriteBatchedStatements: true
        maintainTimeStats: false
        cacheResultSetMetadata: true
        cacheServerConfiguration: true
        elideSetAutoCommits: true

3.2 事务管理问题

// 虚拟线程下的事务管理
@Configuration
@EnableTransactionManagement
public class VirtualThreadTransactionConfig {
    
    @Bean
    public PlatformTransactionManager transactionManager(
            EntityManagerFactory entityManagerFactory) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory);
        
        // 虚拟线程优化
        transactionManager.setNestedTransactionAllowed(true);
        transactionManager.setValidateExistingTransaction(true);
        transactionManager.setGlobalRollbackOnParticipationFailure(false);
        
        return transactionManager;
    }
    
    @Bean
    public TransactionTemplate transactionTemplate(
            PlatformTransactionManager transactionManager) {
        TransactionTemplate template = new TransactionTemplate(transactionManager);
        
        // 配置虚拟线程友好的事务属性
        template.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        template.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
        template.setTimeout(30); // 秒
        template.setReadOnly(false);
        
        return template;
    }
    
    // 虚拟线程感知的事务拦截器
    @Bean
    public TransactionInterceptor transactionInterceptor(
            PlatformTransactionManager transactionManager) {
        TransactionInterceptor interceptor = new TransactionInterceptor();
        interceptor.setTransactionManager(transactionManager);
        
        // 配置事务属性源
        NameMatchTransactionAttributeSource source = 
            new NameMatchTransactionAttributeSource();
        
        Properties props = new Properties();
        props.setProperty("get*", "PROPAGATION_SUPPORTS,readOnly");
        props.setProperty("find*", "PROPAGATION_SUPPORTS,readOnly");
        props.setProperty("*", "PROPAGATION_REQUIRED,-Exception");
        
        source.setProperties(props);
        interceptor.setTransactionAttributeSource(source);
        
        return interceptor;
    }
}

四、ThreadLocal和上下文传递问题

4.1 MDC日志上下文丢失问题

问题现象:

@Slf4j
@Component
public class LoggingService {
    
    public void process() {
        MDC.put("requestId", UUID.randomUUID().toString());
        
        Thread.startVirtualThread(() -> {
            // ❌ MDC上下文丢失
            log.info("Processing in virtual thread");
        });
    }
}
解决方案:
// 方案1:虚拟线程感知的MDC包装器
@Component
public class VirtualThreadMDC {
    
    private static final ThreadLocal<Map<String, String>> VIRTUAL_THREAD_CONTEXT =
        new ThreadLocal<>();
    
    public static void wrap(Runnable task) {
        Map<String, String> context = MDC.getCopyOfContextMap();
        
        Thread virtualThread = Thread.ofVirtual().start(() -> {
            if (context != null) {
                MDC.setContextMap(context);
            }
            try {
                task.run();
            } finally {
                MDC.clear();
            }
        });
    }
    
    public static <T> CompletableFuture<T> wrapAsync(Supplier<T> supplier) {
        Map<String, String> context = MDC.getCopyOfContextMap();
        
        return CompletableFuture.supplyAsync(() -> {
            if (context != null) {
                MDC.setContextMap(context);
            }
            try {
                return supplier.get();
            } finally {
                MDC.clear();
            }
        }, Executors.newVirtualThreadPerTaskExecutor());
    }
    
    // 增强版:支持结构化日志
    public static StructuredTaskWrapper structured() {
        return new StructuredTaskWrapper();
    }
    
    public static class StructuredTaskWrapper {
        private final Map<String, Object> attributes = new HashMap<>();
        
        public StructuredTaskWrapper attribute(String key, Object value) {
            attributes.put(key, value);
            return this;
        }
        
        public void run(Runnable task) {
            Map<String, String> mdcContext = MDC.getCopyOfContextMap();
            
            Thread.startVirtualThread(() -> {
                // 设置MDC
                if (mdcContext != null) {
                    MDC.setContextMap(mdcContext);
                }
                
                // 添加结构化属性
                try (var scope = new StructuredTaskScope()) {
                    // 执行任务
                    task.run();
                } catch (Exception e) {
                    log.error("Virtual thread task failed", e);
                } finally {
                    MDC.clear();
                }
            });
        }
    }
}

// 使用示例
@Service
public class LoggingService {
    
    @Autowired
    private VirtualThreadMDC mdcWrapper;
    
    public void processWithContext() {
        MDC.put("requestId", "req-123");
        MDC.put("userId", "user-456");
        
        // 正确传递MDC
        mdcWrapper.wrap(() -> {
            log.info("Processing with preserved MDC context");
            
            // 嵌套虚拟线程
            mdcWrapper.wrap(() -> {
                log.info("Nested virtual thread with context");
            });
        });
    }
}

// 方案2:AOP切面自动管理MDC
@Aspect
@Component
public class VirtualThreadMDCAspect {
    
    @Around("@annotation(WithVirtualThread)")
    public Object manageMDC(ProceedingJoinPoint joinPoint) throws Throwable {
        Map<String, String> context = MDC.getCopyOfContextMap();
        
        return CompletableFuture.supplyAsync(() -> {
            try {
                // 恢复MDC
                if (context != null) {
                    MDC.setContextMap(context);
                }
                
                // 添加方法信息
                MethodSignature signature = (MethodSignature) joinPoint.getSignature();
                MDC.put("method", signature.getMethod().getName());
                MDC.put("class", joinPoint.getTarget().getClass().getSimpleName());
                
                return joinPoint.proceed();
            } catch (Throwable e) {
                throw new RuntimeException(e);
            } finally {
                MDC.clear();
            }
        }, Executors.newVirtualThreadPerTaskExecutor()).join();
    }
}

// 自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface WithVirtualThread {
    String context() default "";
}

// 使用注解
@Service
public class AsyncService {
    
    @WithVirtualThread
    public CompletableFuture<String> processAsync(String input) {
        log.info("Processing in virtual thread with MDC");
        return CompletableFuture.completedFuture("Processed: " + input);
    }
}

4.2 请求上下文传递问题

// 方案:虚拟线程感知的RequestContextHolder
@Component
public class VirtualThreadRequestContext {
    
    private static final ThreadLocal<RequestAttributes> VIRTUAL_THREAD_REQUEST =
        new ThreadLocal<>();
    
    /**
     * 包装虚拟线程任务,传递请求上下文
     */
    public static Runnable wrapWithContext(Runnable task) {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        
        return () -> {
            try {
                // 设置请求上下文
                if (attributes != null) {
                    RequestContextHolder.setRequestAttributes(attributes, true);
                }
                
                task.run();
            } finally {
                RequestContextHolder.resetRequestAttributes();
            }
        };
    }
    
    /**
     * 异步执行并传递上下文
     */
    public static <T> CompletableFuture<T> supplyAsyncWithContext(
            Supplier<T> supplier) {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        
        return CompletableFuture.supplyAsync(() -> {
            try {
                if (attributes != null) {
                    RequestContextHolder.setRequestAttributes(attributes, true);
                }
                return supplier.get();
            } finally {
                RequestContextHolder.resetRequestAttributes();
            }
        }, Executors.newVirtualThreadPerTaskExecutor());
    }
    
    /**
     * 创建虚拟线程作用域
     */
    public static VirtualThreadScope createScope() {
        return new VirtualThreadScope();
    }
    
    public static class VirtualThreadScope implements AutoCloseable {
        private final Map<Class<?>, Object> beans = new HashMap<>();
        private final RequestAttributes originalAttributes;
        
        public VirtualThreadScope() {
            this.originalAttributes = RequestContextHolder.getRequestAttributes();
        }
        
        public <T> T getOrCreate(Class<T> type, Supplier<T> creator) {
            return type.cast(beans.computeIfAbsent(type, k -> creator.get()));
        }
        
        public void runInScope(Runnable task) {
            Thread.startVirtualThread(() -> {
                try {
                    // 设置请求上下文
                    if (originalAttributes != null) {
                        RequestContextHolder.setRequestAttributes(
                            originalAttributes, true);
                    }
                    
                    // 执行任务
                    task.run();
                } finally {
                    RequestContextHolder.resetRequestAttributes();
                    beans.clear();
                }
            });
        }
        
        @Override
        public void close() {
            beans.clear();
        }
    }
}

// 拦截器:自动传递请求上下文
@Component
public class VirtualThreadContextInterceptor implements AsyncHandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest request, 
                           HttpServletResponse response, 
                           Object handler) {
        // 在虚拟线程中存储请求属性
        request.setAttribute("virtualThreadContext", 
            RequestContextHolder.getRequestAttributes());
        return true;
    }
    
    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request,
                                             HttpServletResponse response,
                                             Object handler) {
        // 异步处理开始
    }
}

// 配置拦截器
@Configuration
public class WebMvcVirtualThreadConfig implements WebMvcConfigurer {
    
    @Autowired
    private VirtualThreadContextInterceptor contextInterceptor;
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(contextInterceptor)
            .addPathPatterns("/api/**");
    }
}

五、异步任务与虚拟线程集成

5.1 @Async虚拟线程配置

@Configuration
@EnableAsync
public class VirtualThreadAsyncConfig implements AsyncConfigurer {
    
    @Value("${async.virtual-threads.core-pool-size:100}")
    private int corePoolSize;
    
    @Value("${async.virtual-threads.max-pool-size:1000}")
    private int maxPoolSize;
    
    @Value("${async.virtual-threads.keep-alive-seconds:60}")
    private int keepAliveSeconds;
    
    @Override
    public Executor getAsyncExecutor() {
        // 创建虚拟线程执行器
        ThreadFactory virtualThreadFactory = Thread.ofVirtual()
            .name("async-vt-", 0)
            .factory();
        
        // 使用虚拟线程执行器
        ExecutorService executor = Executors.newThreadPerTaskExecutor(virtualThreadFactory);
        
        return new DelegatingExecutor(executor) {
            @Override
            public void execute(Runnable task) {
                // 包装任务以传递上下文
                Runnable wrappedTask = VirtualThreadRequestContext.wrapWithContext(task);
                super.execute(wrappedTask);
            }
        };
    }
    
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> {
            log.error("Async method {} failed", method.getName(), ex);
            
            // 虚拟线程特定的异常处理
            if (ex instanceof VirtualThreadException) {
                handleVirtualThreadException((VirtualThreadException) ex);
            }
        };
    }
    
    // 虚拟线程感知的TaskExecutor
    @Bean(name = "virtualThreadTaskExecutor")
    public TaskExecutor virtualThreadTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        
        // 配置虚拟线程执行器
        executor.setThreadFactory(Thread.ofVirtual()
            .name("task-vt-", 0)
            .factory());
        
        // 由于使用虚拟线程,以下参数意义不同
        executor.setCorePoolSize(1);      // 虚拟线程下可设置为1
        executor.setMaxPoolSize(Integer.MAX_VALUE); // 虚拟线程无上限
        executor.setQueueCapacity(0);     // 虚拟线程不使用队列
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(30);
        executor.setThreadNamePrefix("task-vt-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        executor.initialize();
        
        return executor;
    }
    
    // 调度任务虚拟线程支持
    @Bean
    public TaskScheduler virtualThreadTaskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        
        scheduler.setThreadFactory(Thread.ofVirtual()
            .name("scheduler-vt-", 0)
            .factory());
        
        scheduler.setPoolSize(10);  // 调度线程数
        scheduler.setThreadNamePrefix("scheduler-vt-");
        scheduler.setAwaitTerminationSeconds(30);
        scheduler.setWaitForTasksToCompleteOnShutdown(true);
        scheduler.initialize();
        
        return scheduler;
    }
}

// 使用@Async的改进版
@Service
public class AsyncVirtualThreadService {
    
    @Async("virtualThreadTaskExecutor")
    @VirtualThreadContext  // 自定义注解
    public CompletableFuture<String> processAsync(String input) {
        // 在虚拟线程中执行,上下文已自动传递
        log.info("Processing in virtual thread: {}", input);
        
        // 模拟耗时操作
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        
        return CompletableFuture.completedFuture("Processed: " + input);
    }
    
    // 批量虚拟线程处理
    public CompletableFuture<List<String>> processBatch(List<String> inputs) {
        List<CompletableFuture<String>> futures = inputs.stream()
            .map(this::processAsync)
            .collect(Collectors.toList());
        
        return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
            .thenApply(v -> futures.stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList()));
    }
}

// 自定义注解处理器
@Aspect
@Component
public class VirtualThreadContextAspect {
    
    @Around("@annotation(virtualThreadContext)")
    public Object handleVirtualThreadContext(ProceedingJoinPoint joinPoint,
                                            VirtualThreadContext virtualThreadContext)
            throws Throwable {
        
        // 获取当前上下文
        Map<String, String> mdcContext = MDC.getCopyOfContextMap();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        
        // 在虚拟线程中执行
        return CompletableFuture.supplyAsync(() -> {
            try {
                // 恢复上下文
                if (mdcContext != null) {
                    MDC.setContextMap(mdcContext);
                }
                if (requestAttributes != null) {
                    RequestContextHolder.setRequestAttributes(requestAttributes, true);
                }
                
                return joinPoint.proceed();
            } catch (Throwable e) {
                throw new RuntimeException(e);
            } finally {
                // 清理
                MDC.clear();
                RequestContextHolder.resetRequestAttributes();
            }
        }, Executors.newVirtualThreadPerTaskExecutor()).join();
    }
}

5.2 CompletableFuture虚拟线程支持

@Component
public class VirtualThreadCompletableFuture {
    
    private final ExecutorService virtualThreadExecutor;
    
    public VirtualThreadCompletableFuture() {
        // 创建虚拟线程执行器
        this.virtualThreadExecutor = Executors.newThreadPerTaskExecutor(
            Thread.ofVirtual()
                .name("cf-vt-", 0)
                .factory()
        );
    }
    
    /**
     * 在虚拟线程中执行Supplier
     */
    public <T> CompletableFuture<T> supplyAsync(Supplier<T> supplier) {
        return CompletableFuture.supplyAsync(() -> {
            // 自动管理MDC
            Map<String, String> mdcContext = MDC.getCopyOfContextMap();
            try {
                if (mdcContext != null) {
                    MDC.setContextMap(mdcContext);
                }
                return supplier.get();
            } finally {
                MDC.clear();
            }
        }, virtualThreadExecutor);
    }
    
    /**
     * 在虚拟线程中执行Runnable
     */
    public CompletableFuture<Void> runAsync(Runnable runnable) {
        return CompletableFuture.runAsync(() -> {
            Map<String, String> mdcContext = MDC.getCopyOfContextMap();
            try {
                if (mdcContext != null) {
                    MDC.setContextMap(mdcContext);
                }
                runnable.run();
            } finally {
                MDC.clear();
            }
        }, virtualThreadExecutor);
    }
    
    /**
     * 并行执行多个任务
     */
    public <T> CompletableFuture<List<T>> allOf(List<Supplier<T>> suppliers) {
        List<CompletableFuture<T>> futures = suppliers.stream()
            .map(this::supplyAsync)
            .collect(Collectors.toList());
        
        return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
            .thenApply(v -> futures.stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList()));
    }
    
    /**
     * 带超时的虚拟线程执行
     */
    public <T> CompletableFuture<T> supplyAsyncWithTimeout(
            Supplier<T> supplier, long timeout, TimeUnit unit) {
        return supplyAsync(supplier)
            .orTimeout(timeout, unit)
            .exceptionally(ex -> {
                if (ex instanceof TimeoutException) {
                    log.warn("Virtual thread task timeout after {} {}", timeout, unit);
                    return null;
                }
                throw new CompletionException(ex);
            });
    }
    
    @PreDestroy
    public void shutdown() {
        virtualThreadExecutor.shutdown();
        try {
            if (!virtualThreadExecutor.awaitTermination(30, TimeUnit.SECONDS)) {
                virtualThreadExecutor.shutdownNow();
            }
        } catch (InterruptedException e) {
            virtualThreadExecutor.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}

六、监控和诊断配置

6.1 虚拟线程监控

@Component
@Slf4j
public class VirtualThreadMonitor {
    
    private final ScheduledExecutorService monitorScheduler;
    private final Map<String, VirtualThreadStats> threadStats = new ConcurrentHashMap<>();
    
    public VirtualThreadMonitor() {
        this.monitorScheduler = Executors.newScheduledThreadPool(1);
    }
    
    @PostConstruct
    public void startMonitoring() {
        // 每5秒收集一次虚拟线程统计信息
        monitorScheduler.scheduleAtFixedRate(() -> {
            try {
                collectVirtualThreadStats();
                logVirtualThreadMetrics();
                checkForProblems();
            } catch (Exception e) {
                log.error("Failed to collect virtual thread stats", e);
            }
        }, 5, 5, TimeUnit.SECONDS);
        
        // 注册JMX Bean
        registerJmxBean();
    }
    
    private void collectVirtualThreadStats() {
        Thread.getAllStackTraces().forEach((thread, stackTrace) -> {
            if (thread.isVirtual()) {
                String threadName = thread.getName();
                VirtualThreadStats stats = threadStats.computeIfAbsent(
                    threadName, k -> new VirtualThreadStats());
                
                stats.update(thread, stackTrace);
            }
        });
        
        // 清理过期的线程统计
        cleanupOldStats();
    }
    
    private void logVirtualThreadMetrics() {
        long virtualThreadCount = threadStats.size();
        long pinnedThreads = threadStats.values().stream()
            .filter(VirtualThreadStats::isPinned)
            .count();
        
        double avgCpuTime = threadStats.values().stream()
            .mapToLong(VirtualThreadStats::getCpuTime)
            .average()
            .orElse(0);
        
        log.info("Virtual Thread Metrics - Count: {}, Pinned: {}, Avg CPU: {}ms", 
            virtualThreadCount, pinnedThreads, avgCpuTime);
        
        // 详细统计
        if (log.isDebugEnabled()) {
            threadStats.forEach((name, stats) -> {
                log.debug("Thread {}: state={}, cpu={}ms, user={}ms", 
                    name, stats.getState(), stats.getCpuTime(), stats.getUserTime());
            });
        }
    }
    
    private void checkForProblems() {
        // 检查是否有线程被pin住
        threadStats.entrySet().stream()
            .filter(entry -> entry.getValue().isPinned())
            .forEach(entry -> {
                log.warn("Virtual thread {} is pinned! Stack trace:\n{}",
                    entry.getKey(), entry.getValue().getStackTrace());
            });
        
        // 检查CPU使用率过高的线程
        threadStats.entrySet().stream()
            .filter(entry -> entry.getValue().getCpuTime() > 1000) // 超过1秒
            .forEach(entry -> {
                log.warn("Virtual thread {} using high CPU: {}ms",
                    entry.getKey(), entry.getValue().getCpuTime());
            });
    }
    
    private void registerJmxBean() {
        try {
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            ObjectName name = new ObjectName("com.example:type=VirtualThreadMonitor");
            mbs.registerMBean(new VirtualThreadMonitorMXBean() {
                @Override
                public long getVirtualThreadCount() {
                    return threadStats.size();
                }
                
                @Override
                public long getPinnedThreadCount() {
                    return threadStats.values().stream()
                        .filter(VirtualThreadStats::isPinned)
                        .count();
                }
                
                @Override
                public Map<String, String> getThreadStates() {
                    return threadStats.entrySet().stream()
                        .collect(Collectors.toMap(
                            Map.Entry::getKey,
                            e -> e.getValue().getState().toString()
                        ));
                }
            }, name);
        } catch (Exception e) {
            log.error("Failed to register JMX bean", e);
        }
    }
    
    @PreDestroy
    public void stopMonitoring() {
        monitorScheduler.shutdown();
    }
    
    private static class VirtualThreadStats {
        private Thread.State state;
        private long cpuTime;
        private long userTime;
        private boolean pinned;
        private StackTraceElement[] stackTrace;
        private long lastUpdateTime;
        
        void update(Thread thread, StackTraceElement[] stackTrace) {
            this.state = thread.getState();
            this.cpuTime = thread.isAlive() ? 
                ManagementFactory.getThreadMXBean().getThreadCpuTime(thread.getId()) / 1_000_000 : 0;
            this.userTime = thread.isAlive() ?
                ManagementFactory.getThreadMXBean().getThreadUserTime(thread.getId()) / 1_000_000 : 0;
            this.pinned = isThreadPinned(thread);
            this.stackTrace = stackTrace;
            this.lastUpdateTime = System.currentTimeMillis();
        }
        
        private boolean isThreadPinned(Thread thread) {
            // 简化实现:检查线程是否在某个状态停留过久
            return thread.getState() == Thread.State.RUNNABLE && 
                   cpuTime > 100; // 超过100ms可能是pin住
        }
        
        // Getters...
    }
    
    public interface VirtualThreadMonitorMXBean {
        long getVirtualThreadCount();
        long getPinnedThreadCount();
        Map<String, String> getThreadStates();
    }
}

6.2 Micrometer监控集成

@Configuration
public class VirtualThreadMetricsConfig {
    
    @Bean
    public MeterBinder virtualThreadMeterBinder() {
        return registry -> {
            // 虚拟线程数量
            Gauge.builder("jvm.virtual.threads.count", 
                    () -> Thread.getAllStackTraces().keySet().stream()
                        .filter(Thread::isVirtual)
                        .count())
                .description("Number of virtual threads")
                .tag("type", "virtual")
                .register(registry);
            
            // 平台线程数量
            Gauge.builder("jvm.platform.threads.count",
                    () -> Thread.getAllStackTraces().keySet().stream()
                        .filter(t -> !t.isVirtual())
                        .count())
                .description("Number of platform threads")
                .tag("type", "platform")
                .register(registry);
            
            // 虚拟线程状态分布
            for (Thread.State state : Thread.State.values()) {
                Gauge.builder("jvm.virtual.threads.state",
                        () -> Thread.getAllStackTraces().keySet().stream()
                            .filter(Thread::isVirtual)
                            .filter(t -> t.getState() == state)
                            .count())
                    .description("Virtual threads in state " + state)
                    .tag("state", state.name().toLowerCase())
                    .register(registry);
            }
            
            // 虚拟线程创建速率
            Counter.builder("jvm.virtual.threads.created")
                .description("Total virtual threads created")
                .register(registry);
            
            // CPU时间统计
            Timer.builder("jvm.virtual.threads.cpu.time")
                .description("CPU time used by virtual threads")
                .publishPercentiles(0.5, 0.95, 0.99)
                .register(registry);
        };
    }
    
    @Bean
    public TimedAspect timedAspect(MeterRegistry registry) {
        return new TimedAspect(registry);
    }
    
    @Bean
    public CountedAspect countedAspect(MeterRegistry registry) {
        return new CountedAspect(registry);
    }
}

// 虚拟线程感知的指标收集
@Component
public class VirtualThreadMetricsCollector {
    
    private final MeterRegistry meterRegistry;
    private final Map<Long, Long> threadStartTimes = new ConcurrentHashMap<>();
    
    public VirtualThreadMetricsCollector(MeterRegistry meterRegistry) {
        this.meterRegistry = meterRegistry;
        
        // 注册虚拟线程创建监听器
        Thread.Builder virtualThreadBuilder = Thread.ofVirtual()
            .name("monitored-vt-", 0)
            .allowSetThreadLocals(true)
            .inheritInheritableThreadLocals(true);
            
        // 使用增强的ThreadFactory
        ThreadFactory monitoredFactory = runnable -> {
            Thread thread = virtualThreadBuilder.unstarted(runnable);
            
            // 记录线程创建
            Counter createdCounter = Counter.builder("jvm.virtual.threads.created")
                .tag("name", thread.getName())
                .register(meterRegistry);
            createdCounter.increment();
            
            threadStartTimes.put(thread.getId(), System.nanoTime());
            
            return thread;
        };
    }
    
    public void recordThreadCompletion(long threadId) {
        Long startTime = threadStartTimes.remove(threadId);
        if (startTime != null) {
            long duration = System.nanoTime() - startTime;
            
            Timer.Sample sample = Timer.start(meterRegistry);
            sample.stop(Timer.builder("jvm.virtual.threads.lifetime")
                .description("Virtual thread lifetime")
                .publishPercentiles(0.5, 0.95, 0.99)
                .register(meterRegistry));
        }
    }
}

七、最佳实践配置总结

7.1 完整配置示例

# application.yml - 虚拟线程完整配置
spring:
  application:
    name: virtual-thread-demo
  
  # 虚拟线程配置
  virtual-threads:
    enabled: true
    mode: hybrid  # hybrid|virtual-only|platform-only
    executor:
      core-pool-size: 1
      max-pool-size: 10000
      keep-alive-seconds: 60
      thread-name-prefix: "app-vt-"
    tomcat:
      enabled: true
      max-connections: 10000
      connection-timeout: 30s
    database:
      connection-pool:
        max-size: 50
        validation-query: "SELECT 1"
        leak-detection-threshold: 60s
  
  # 数据源配置
  datasource:
    hikari:
      maximum-pool-size: 50
      minimum-idle: 5
      connection-timeout: 30000
      idle-timeout: 600000
      max-lifetime: 1800000
      data-source-properties:
        useVirtualThreads: true
        cachePrepStmts: true
        prepStmtCacheSize: 250
  
  # 异步配置
  task:
    execution:
      pool:
        core-size: 1
        max-size: 10000
        queue-capacity: 0
        keep-alive: 60s
        thread-name-prefix: "async-vt-"
    scheduling:
      pool:
        size: 10
        thread-name-prefix: "sched-vt-"
  
  # JPA配置
  jpa:
    properties:
      hibernate:
        connection.handling_mode: DELAYED_ACQUISITION_AND_HOLD
        jdbc.batch_size: 20
        order_inserts: true
        order_updates: true
  
  # 监控配置
  management:
    endpoints:
      web:
        exposure:
          include: health,info,metrics,prometheus,threaddump
    metrics:
      export:
        prometheus:
          enabled: true
      tags:
        application: ${spring.application.name}
        environment: ${ENV:local}
    endpoint:
      health:
        show-details: always

# 日志配置
logging:
  pattern:
    level: "%5p [${spring.application.name},%X{traceId:-},%X{spanId:-},%thread]"
  level:
    org.springframework: INFO
    com.example: DEBUG

# 虚拟线程性能调优
virtual-thread-tuning:
  pinning-threshold-ms: 100
  stack-size-kb: 1024
  carrier-thread-count: ${CPU_COUNT:8}
  monitor-enabled: true
  monitor-interval-ms: 5000

7.2 主配置类

@SpringBootApplication
@EnableAsync
@EnableScheduling
@EnableTransactionManagement
@EnableConfigurationProperties({
    VirtualThreadProperties.class,
    VirtualThreadTuningProperties.class
})
public class VirtualThreadApplication {
    
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(VirtualThreadApplication.class);
        
        // 设置虚拟线程相关的系统属性
        System.setProperty("spring.threads.virtual.enabled", "true");
        System.setProperty("jdk.virtualThreadScheduler.parallelism", 
            String.valueOf(Runtime.getRuntime().availableProcessors()));
        System.setProperty("jdk.virtualThreadScheduler.maxPoolSize", "256");
        
        app.run(args);
    }
    
    @Bean
    public CommandLineRunner virtualThreadInfo() {
        return args -> {
            log.info("Virtual threads enabled: {}", 
                Thread.currentThread().isVirtual() || 
                ManagementFactory.getThreadMXBean().isVirtualThreadsSupported());
            
            log.info("Available processors: {}", 
                Runtime.getRuntime().availableProcessors());
            
            log.info("JVM version: {}", 
                System.getProperty("java.version"));
        };
    }
}

// 虚拟线程配置属性类
@ConfigurationProperties(prefix = "spring.virtual-threads")
@Data
public class VirtualThreadProperties {
    
    private boolean enabled = true;
    private Mode mode = Mode.HYBRID;
    private ExecutorConfig executor = new ExecutorConfig();
    private TomcatConfig tomcat = new TomcatConfig();
    private DatabaseConfig database = new DatabaseConfig();
    
    public enum Mode {
        HYBRID,      // 混合模式
        VIRTUAL_ONLY, // 仅虚拟线程
        PLATFORM_ONLY // 仅平台线程
    }
    
    @Data
    public static class ExecutorConfig {
        private int corePoolSize = 1;
        private int maxPoolSize = 10000;
        private int keepAliveSeconds = 60;
        private String threadNamePrefix = "app-vt-";
        private boolean allowCoreThreadTimeout = true;
        private boolean prestartAllCoreThreads = false;
    }
    
    @Data
    public static class TomcatConfig {
        private boolean enabled = true;
        private int maxConnections = 10000;
        private Duration connectionTimeout = Duration.ofSeconds(30);
        private int maxThreads = 1000;
        private int minSpareThreads = 10;
        private int acceptorThreadCount = 1;
    }
    
    @Data
    public static class DatabaseConfig {
        private ConnectionPool connectionPool = new ConnectionPool();
        
        @Data
        public static class ConnectionPool {
            private int maxSize = 50;
            private int minIdle = 5;
            private String validationQuery = "SELECT 1";
            private Duration leakDetectionThreshold = Duration.ofSeconds(60);
            private boolean cachePrepStmts = true;
            private int prepStmtCacheSize = 250;
        }
    }
}

7.3 健康检查

@Component
public class VirtualThreadHealthIndicator implements HealthIndicator {
    
    private final VirtualThreadMonitor monitor;
    private final VirtualThreadProperties properties;
    
    public VirtualThreadHealthIndicator(VirtualThreadMonitor monitor,
                                       VirtualThreadProperties properties) {
        this.monitor = monitor;
        this.properties = properties;
    }
    
    @Override
    public Health health() {
        if (!properties.isEnabled()) {
            return Health.up()
                .withDetail("enabled", false)
                .build();
        }
        
        try {
            long virtualThreadCount = Thread.getAllStackTraces().keySet().stream()
                .filter(Thread::isVirtual)
                .count();
            
            long pinnedThreads = Thread.getAllStackTraces().keySet().stream()
                .filter(Thread::isVirtual)
                .filter(this::isPinned)
                .count();
            
            Health.Builder builder = Health.up()
                .withDetail("virtualThreads.count", virtualThreadCount)
                .withDetail("virtualThreads.pinned", pinnedThreads)
                .withDetail("mode", properties.getMode().toString());
            
            // 检查是否有问题
            if (pinnedThreads > virtualThreadCount * 0.1) {
                // 超过10%的虚拟线程被pin住
                builder.down()
                    .withDetail("reason", "Too many pinned virtual threads")
                    .withDetail("pinnedPercentage", 
                        String.format("%.1f%%", (pinnedThreads * 100.0 / virtualThreadCount)));
            }
            
            return builder.build();
            
        } catch (Exception e) {
            return Health.down(e)
                .withDetail("error", e.getMessage())
                .build();
        }
    }
    
    private boolean isPinned(Thread thread) {
        // 简化实现:检查线程状态和CPU时间
        ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
        long cpuTime = threadBean.getThreadCpuTime(thread.getId());
        
        return thread.getState() == Thread.State.RUNNABLE && 
               cpuTime > 100_000_000; // 100ms
    }
}

7.4 调试和故障排除

@Component
@ConditionalOnProperty(name = "virtual-thread-tuning.debug", havingValue = "true")
public class VirtualThreadDebugger {
    
    private final ThreadMXBean threadBean;
    private final Map<Long, ThreadDebugInfo> debugInfos = new ConcurrentHashMap<>();
    
    public VirtualThreadDebugger() {
        this.threadBean = ManagementFactory.getThreadMXBean();
        this.threadBean.setThreadContentionMonitoringEnabled(true);
        this.threadBean.setThreadCpuTimeEnabled(true);
    }
    
    public void startMonitoring(Thread thread) {
        if (thread.isVirtual()) {
            ThreadDebugInfo info = new ThreadDebugInfo(thread);
            debugInfos.put(thread.getId(), info);
            
            // 设置UncaughtExceptionHandler
            thread.setUncaughtExceptionHandler((t, e) -> {
                log.error("Virtual thread {} failed", t.getName(), e);
                debugInfos.remove(t.getId());
            });
        }
    }
    
    public void recordEvent(long threadId, String event, Object data) {
        ThreadDebugInfo info = debugInfos.get(threadId);
        if (info != null) {
            info.recordEvent(event, data);
        }
    }
    
    public void dumpDebugInfo() {
        debugInfos.forEach((id, info) -> {
            log.info("Thread {} ({}):", info.getThreadName(), info.getThreadId());
            log.info("  State: {}", info.getState());
            log.info("  CPU Time: {}ms", info.getCpuTime() / 1_000_000);
            log.info("  User Time: {}ms", info.getUserTime() / 1_000_000);
            log.info("  Blocked Count: {}", info.getBlockedCount());
            log.info("  Waited Count: {}", info.getWaitedCount());
            
            if (!info.getEvents().isEmpty()) {
                log.info("  Events:");
                info.getEvents().forEach((time, event) -> {
                    log.info("    {}: {}", time, event);
                });
            }
            
            // 栈轨迹
            if (log.isDebugEnabled()) {
                log.debug("  Stack Trace:");
                for (StackTraceElement element : info.getStackTrace()) {
                    log.debug("    {}", element);
                }
            }
        });
    }
    
    private static class ThreadDebugInfo {
        private final long threadId;
        private final String threadName;
        private final Thread thread;
        private final Map<Long, String> events = new LinkedHashMap<>();
        
        ThreadDebugInfo(Thread thread) {
            this.threadId = thread.getId();
            this.threadName = thread.getName();
            this.thread = thread;
        }
        
        void recordEvent(String event, Object data) {
            events.put(System.currentTimeMillis(), 
                event + (data != null ? ": " + data : ""));
        }
        
        // Getters...
    }
}

通过以上详细的配置和解决方案,可以有效地在Spring Boot 3.x中集成和使用虚拟线程,充分发挥其高并发优势,同时避免常见的集成问题。

虚拟线程在SpringBoot中的应用——鸟枪换大炮 从上面的性能对比来看,虚拟线程在性能方面有明显的优势,但是要注意的是,我们上面的测试都是让线程等待了50ms,这是模拟什么场景?没错,是IO密集型场景,即线程大部分时间是在等待IO,这样虚拟线程才可以发挥出它的优势,如果是CPU密集型场景,那么可能效果并不大。不过我们目前大部分的应用都是IO密集型应用较多,比如典型的WEB应用,大量的时间在等待网络IO(DB、缓存、HTTP等等),使用虚拟线程的效果还是非常明显的。 阅读详情

相关推荐

性能比较 - Spring Boot 应用程序中的线程池与虚拟线程 (Project Loom)

因此,在本文中,我们还将探索使用虚拟线程来处理请求。但请注意,在不考虑系统容量和资源限制的情况下增加线程池中的线程数量可能会对性能、稳定性和整体系统行为产生不利影响。与本机线程相比,虚拟线程的内存占用量显着降低,允许应用程序创建和管理更多数量的线程,而不会耗尽系统资源。但需要注意的是,线程池和 WebFlux 都有各自的优点和缺点,选择取决于具体要求、工作负载的性质以及开发团队的专业知识。因此,我们可以初步得出结论,Java 21中虚拟线程的发布将显着改变现有服务器和框架中请求处理的方法。

程序猿大波的博客 2995

性能提升 200% !SpringBoot 虚拟线程来啦!!

什么是 Project Loom?这是 Oracle 的一个新项目,主要目标是显著减少编写、维护和观察高吞吐量并发应用程序的工作量。换句话说,Project Loom 旨在支持和推进一个高吞吐量、轻量级的 Java 并发模型,因为传统的操作系统线程(Java 并发模型的核心)有一些缺点,并且在计算上相当昂贵。反之,虚拟线程是更轻量级的线程,不与操作系统线程连接(由 JVM 管理)。这意味着虚拟线程是“每请求对应一个线程”编程的理想选择,可以创建大量的虚拟线程,而不会降低吞吐量。

IT界那些事儿 4308

LangChain4j与Spring Boot 4整合:构建Java AI智能体应用实践

在AI应用开发领域,智能体(Agent)作为能够理解意图、规划步骤并调用工具执行任务的核心概念,正成为连接大语言模型与实际业务场景的关键技术。其工作原理通常基于ReAct等框架,通过与大模型交互实现推理与行动的循环。这一架构的技术价值在于,它将生成式AI的认知能力与外部系统(如数据库、API)的执行能力相结合,从而能够处理复杂、多步骤的自动化任务。在应用场景上,智能体广泛应用于智能客服、自动化助手、数据分析与报告生成等领域,显著提升了人机交互的效率和智能化水平。本文聚焦于如何在Java技术栈中实现这一能力,

weixin_33798152的博客 981

SpringBoot3 使用虚拟线程

用最简单的方式使用虚拟线程

yaobo2816的专栏 1847

【SpringBoot 3.x 第45节】虚拟线程都上桌了,你还在拧线程池参数?——Spring Boot 3.2 的 Virtual Threads 从“开关”到“上生产”的全套实战!

🏆本文收录于《滚雪球学SpringBoot 3》,专门攻坚指数提升,本年度国内最系统+最专业+最详细(永久更新)。

**My Coding Family** 919

【SpringBoot 4.x 第139节】虚拟线程在 Spring Boot 中的应用:适用场景与风险!

🏆 本文收录于 《滚雪球学 Spring Boot 4.x》 专栏。本专栏面向 有一定 Java 基础,但尚未系统学习 Spring Boot 的读者,采用“滚雪球式学习法”:先跑通、再理解、再重构、再上线,带你从第一个 Hello API 开始,逐步完成一个可部署、可监控、可扩展的后端项目。

**My Coding Family** 138

Java 21+ 现代 JVM 专家 Agent 实战指南:从虚拟线程到 Spring Boot 3.x 的企业级开发能力解析

> 本文以 GitHub 推荐项目精选 agents24/agents 仓库中的 [java-pro](https://link.gitcode.com/i/44cae192fd6e54c45517437d0f6f2860) 专用 Agent 定义文档为核心,系统拆解该 Agent 所承载的现代 Java 21+ 开发能力矩阵:虚拟线程与结构化并发、Spring Boot 3.x 生态、Graal

gitblog_00304的博客 1073

GBASE南大通用GBase 8s数据库-从零开始的手动安装与实例配置指南

本文详细介绍了GBASE南大通用GBase 8s数据库的手动安装与实例配置全过程,包括环境准备、用户创建、安装包准备、实例创建、环境变量配置等关键步骤。通过实战经验分享和常见问题解决方案,帮助用户快速掌握GBase 8s数据库的安装与配置技巧,确保数据库稳定运行。

weixin_29209825的博客 459

JDK 21虚拟线程在Spring Boot中的性能优化实践

虚拟线程是JDK 21引入的轻量级线程模型,通过用户态调度和协作式任务切换,大幅提升Java应用的并发处理能力。相比传统操作系统线程,虚拟线程创建成本低且不受内核限制,特别适合高并发IO密集型场景。在Spring Boot应用中,只需简单配置即可启用虚拟线程,Tomcat等Web容器能轻松支持数万并发连接。通过电商系统实测,相同硬件下QPS提升近3倍,响应时间降低67%。该技术显著降低了异步编程复杂度,同时保持同步代码的调试便利性,是替代CompletableFuture和Reactive编程的高效方案。

weixin_34116110的博客 395

CentOS 9 Stream 上安装 MySQL 8.0+

根据提示进行设置,包括设置新的 root 密码、禁用远程 root 登录等。MySQL 在首次安装时会生成一个临时密码。这样就完成了 MySQL 8.0.37 的安装。这将安装最新的 MySQL 8.0 版本。

小强不是坑 1683

Vivado DDR IP自定义型号避坑指南:如何正确填写CSV参数表(附常见错误排查)

本文详细解析了Vivado DDR IP自定义型号配置中的关键步骤与常见问题,特别针对DDR4内存颗粒的参数提取、CSV参数表填写误区及故障排查提供了实用指南。通过实际案例和调试技巧,帮助工程师避免配置陷阱,提升DDR4系统稳定性和性能。

weixin_29280657的博客 418

Java 21安装配置与Spring Boot 3.5虚拟线程实战

Java 21作为长期支持版本,正式转正了虚拟线程、分代ZGC和switch模式匹配等特性。虚拟线程由JVM调度,底层复用少量平台线程,创建与切换成本极低,让IO密集型应用轻松支撑十万级并发。在Spring Boot 3.5中,通过一行配置即可为Web容器开启虚拟线程,有效提升高并发场景下的吞吐量。同时,分代ZGC优化了大堆场景的回收效率,降低了Full GC概率。从JDK 21的下载安装、环境变量配置,到与Spring Boot 3.5整合的完整实操路径,这里提供了详细步骤与避坑指南,适合正在选型升级或希

weixin_34080951的博客 385

STM32最小系统硬件组成详解

STM32最小系统硬件组成详解 0组成: 电源 复位 时钟 调试接口 启动 1、电源 : 一般3.3V LDO供电 加多个0.01uf去耦电容 2、复位:有三种复位方式:上电复位、手动复位、程序自动复位 通常低电平复位:(51单片机高电平复位,电容电阻位置调换) 上电复位,在上电瞬间,电容充电,RESET出现短暂的低电平,该低电平持续时间由电阻和电容共同决定,计...

alala120的博客 12万+

Java 21 LTS 升级实战:Spring Boot 3.x 项目迁移与 3 大兼容性陷阱解析

本文详细解析了Java 21 LTS升级至Spring Boot 3.x项目的实战经验,重点探讨了3大兼容性陷阱及其解决方案。通过虚拟线程、分代ZGC等新特性,显著提升系统性能和开发效率,适用于中大型软件开发项目。文章提供了完整的迁移路线图、关键组件适配指南和验证监控方案,助力开发者顺利完成升级。

chuange6363的博客 326

Qwen-Image LoRA训练实战:从数据准备到异常修复的全流程解析

本文详细解析了Qwen-Image LoRA训练的全流程,从数据准备到参数优化再到异常修复。通过实战案例展示了如何利用LoRA技术微调Qwen-Image模型,提升中文场景下的图像生成质量,特别针对手脚生成异常等问题提供了有效解决方案。文章还分享了中文提示词优化技巧和高级训练方法,帮助开发者高效训练出高质量的LoRA模型。

lemon的博客 973

qwen2vl ValueError: Image features and image tokens do not match: tokens: 568, features 600

本文介绍了一个用于计算多模态数据集中样本token数量的Python工具,特别针对包含文本和图像的Qwen2-VL模型数据集。

q742971636的博客 1021

Java 21升级指南:安装配置、验证与Spring Boot虚拟线程实战

Java 版本迭代加快,LTS 成为企业技术选型的核心依据。安装 JDK 时,若 JAVA_HOME 与 PATH 配置不当,java -version 可能仍指向旧版本,这是升级失败的常见原因。Java 21 作为最新 LTS,其虚拟线程特性可大幅改善高并发 IO 密集型应用的吞吐能力。Spring Boot 3.5 通过一行配置即可启用虚拟线程,让传统同步编程模型直接获得并发红利。从 Java 21 的下载渠道、安装步骤、环境变量验证,到 Spring Boot 中的虚拟线程适配,这里整理出一条完整的升

weixin_33922670的博客 282

Pyinstaller打包为可执行文件编码错误的问题

Pyinstaller打包为可执行文件编码错误的问题 写好的python程序在vscode上运行没有任何问题,将程序利用pyinstaller打包后,运行程序发生了错误。 错误代码 UnicodeDecodeError: ‘utf-8' codec can't decode byte 0xce in position 20-21:invalid cotinuation byte 网上找到的解决方案是: 1.在命令行中输入 chcp 65001 2.按正常方式进行封装 pyinstaller

xuefeng_he的博客 1560

JAVA笔记之虚拟线程Virtual Thread

虚拟线程(Virtual Threads) 是 JDK 21(JEP 444)正式提供的轻量级线程,由 JVM 调度,挂载在少量 载体线程(carrier / platform thread) 上。映射1:1 OS 线程多对少,JVM 调度创建成本高(~MB 栈、内核参与)低,可百万级适用场景CPU 密集、需固定线程亲和I/O 密集、高并发阻塞代码编程模型传统Thread同步阻塞写法 + 高并发HTTP/RPC、JDBC、文件/网络阻塞 I/O。长时间 CPU 计算(应交给。

sinat_39125415的博客 737

PMP–一、二、三模–分类–13.干系人管理

A:确认是否已制定沟通管理计划,使业务干系人认识到项目的成功之处。B:让业务干系人参加冲刺回顾会议。C:与发起人和关键干系人一起确定产品待办事项列表中的优先要务,以便交付商业利益。D:为关键干系人开展收尾调研。C。

stqer的博客 1421

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

Java 21 虚拟线程实战:Spring Boot 并发性能、线程固定与排障指南

Java 21 将虚拟线程正式带入生产环境,Spring Boot 也提供了开箱即用的支持。虚拟线程能够显著降低阻塞式高并发应用的线程成本,但它并不会让单个任务执行得更快,也无法突破数据库连接池、下游限流和 CPU 等资源上限。本文通过可运行示例讲解 Spring Boot 虚拟线程的启用方式、适用场景、性能测试方法和资源治理原则,并重点分析 Pinned Virtual Thread 的成因以及使用 JFR、`jcmd` 定位线程固定问题的方法。

2503_94661781的博客 265

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

Spring Boot 3.5与MyBatis整合深度解析与优化实践

ORM框架作为Java企业级应用的核心组件,通过对象关系映射技术实现数据库操作的高效封装。MyBatis以其独特的SQL灵活性设计,在需要精细控制查询性能的金融、大数据等场景中展现优势。其核心原理基于动态代理机制,将Mapper接口转化为可执行的SQL语句,同时支持XML与注解两种映射方式。在Spring Boot生态中,通过自动配置实现零样板代码整合,最新版本更可利用Java 17的record特性简化DTO设计。针对高频的企业级需求,二级缓存优化可采用Redis分布式方案,而虚拟线程技术能显著提升IO密

weixin_30268921的博客 434

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain&#39;s apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath(&#39;DeepLearnToolbox&#39;));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand(&#39;state&#39;,0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = &#39;sigm&#39;;%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, &#39;Too big error&#39;);```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, &#39;Too big error&#39;);```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Spring Boot虚拟线程压测翻车?瓶颈竟在数据库连接池

虚拟线程是Java 21引入的轻量级并发机制,能以极低的内存成本创建成千上万个线程,理论上可大幅提升应用的并发处理能力。然而在实际落地中,虚拟线程只优化了请求处理线程的调度效率,并不能替代数据库连接、HTTP连接等重量级资源。当Spring Boot开启虚拟线程后,高并发请求会瞬时涌入,将原本被平台线程数掩盖的下游资源瓶颈彻底暴露,最常见的便是HikariCP连接池被打满,导致请求集体超时。通过线程转储可快速定位卡点,并需结合连接池容量评估、锁竞争优化以及异步任务虚拟线程化等手段进行系统性治理。本文基于一次

weixin_33866037的博客 694

Java 21虚拟线程技术解析与高并发实践

虚拟线程是Java并发编程的重要革新,通过M:N调度模型实现轻量级线程管理。相较于传统平台线程1:1绑定操作系统线程的机制,虚拟线程由JVM动态调度到少量载体线程执行,显著降低内存消耗并提升并发能力。这项技术特别适用于IO密集型场景,如微服务调用、数据库访问等,能有效解决线程资源瓶颈问题。在Java 21中,通过Thread.startVirtualThread()和Executors.newVirtualThreadPerTaskExecutor()等API可以快速实现线程模型升级。结合Spring Bo

dggnqzt6462的博客 368

Java 21迁移实战:Spring Boot 3.x升级路径与AI辅助开发指南

Java升级迫在眉睫:2026开发者必须掌握的迁移指南 2026年Q3数据显示,头部企业已完成SpringBoot3.x和Java17的全面迁移,JDK8因安全漏洞、性能落后和人才需求变化面临淘汰。升级核心在于: 安全合规:JDK8已停止维护,无法满足金融、医疗等行业的等保要求; 性能飞跃:ZGC、虚拟线程等技术将并发能力提升10倍; 职业需求:AI相关岗位缺口达40万,Java17成为招聘硬门槛。 迁移路径:分阶段升级至SpringBoot3.x+Java17,重点解决jakarta包替换、依赖冲突等问题

CalEx_Tech的博客 459

Java深入解析篇四十七之虚拟线程

虚拟线程(Virtual Thread)是 JDK 21 正式引入的轻量级线程实现(JEP 444),由 JVM 而非操作系统调度。它保留了 的完整 API,但底层采用 M:N 调度模型,将大量虚拟线程映射到少量平台线程(载体线程)上执行。核心设计目标: 根本矛盾:虚拟线程的解法: 二、虚拟线程 vs 平台线程 2.1 架构对比 2.2 核心差异详解 维度 平台线程 虚拟线程 底层实现 OS 线程(pthread/WinThread) JVM Continuation 对象 栈内存

萧瑟余晖的博客 1292
上一篇: STM32(STM32F103C8T6) 从点灯到深入指南
下一篇: DetectionLab 环境搭建与实战指南
深山技术宅
博客等级 码龄4年 1913粉丝 1746原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值