使用 SpringBoot + 虚拟线程将服务性能提升几百倍!

开发 前端
在前端页面中增加了send10000Requests函数,用于异步发送 10000 个请求。在服务端的日志中可以比较两种线程执行的性能差异。

虚拟线程简介

虚拟线程是 Java 平台的一项创新特性。虚拟线程是一种轻量级的线程实现,它在操作系统层面并不对应真实的内核线程,而是由 JVM 进行管理和调度。这使得可以在不消耗大量系统资源的情况下创建大量的线程,从而能够更高效地处理并发任务。

虚拟线程与普通线程的区别

  1. 资源消耗:普通线程通常与操作系统的内核线程直接对应,创建和切换成本较高,资源消耗大。虚拟线程则轻量得多,创建和切换成本极低,能够创建大量的虚拟线程而不会导致系统资源紧张。
  2. 调度方式:普通线程的调度由操作系统内核负责,而虚拟线程的调度由 JVM 管理,更加灵活高效。
  3. 并发能力:由于虚拟线程的低消耗特性,可以创建更多的虚拟线程来处理并发任务,从而提高系统的并发处理能力。

项目创建及依赖配置(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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>virtual-thread-performance-booster</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Virtual Thread Performance Booster</name>

    <properties>
        <java.version>19</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

配置文件(application.yml)

server:
  port: 8080
thread:
  core-pool-size: 10
  max-connections: 2000
  max-threads: 500

线程配置类

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
@EnableAsync
public class ThreadConfig {

    @Value("${thread.core-pool-size}")
    private int corePoolSize;

    @Value("${thread.max-connections}")
    private int maxConnections;

    @Value("${thread.max-threads}")
    private int maxThreads;

    @Bean(name = "asyncTaskExecutor")
    public ThreadPoolTaskExecutor asyncTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxThreads);
        executor.setQueueCapacity(maxConnections);
        executor.setThreadNamePrefix("Async-");
        executor.initialize();
        return executor;
    }

    @Bean(name = "virtualThreadExecutor")
    public ExecutorService virtualThreadExecutor() {
        return Executors.newVirtualThreadPerTaskExecutor();
    }
}

TomcatProtocolHandlerCustomizer 类

import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.stereotype.Component;

@Component
public class TomcatProtocolHandlerCustomizer implements TomcatConnectorCustomizer {

    @Value("${thread.max-connections}")
    private int maxConnections;

    @Value("${thread.max-threads}")
    private int maxThreads;

    @Override
    public void customize(Connector connector) {
        Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
        protocol.setMaxConnections(maxConnections);
        protocol.setMaxThreads(maxThreads);
        protocol.setMinSpareThreads(50);
    }
}

服务类

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ExecutorService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class VirtualThreadService {

    // 获取虚拟线程执行器
    @Autowired
    private ExecutorService virtualThreadExecutor;

    // 获取异步任务执行器
    @Autowired
    private ThreadPoolTaskExecutor asyncTaskExecutor;

    @Async("asyncTaskExecutor")
    public void performVirtualThreadTask() {
        Instant start = Instant.now();
        virtualThreadExecutor.execute(() -> {
            // 模拟耗时任务
            try {
                Thread.sleep(5000);
                System.out.println("虚拟线程任务完成!");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Instant end = Instant.now();
        long duration = Duration.between(start, end).toMillis();
        System.out.println("虚拟线程方法执行时间: " + duration + " 毫秒");
    }

    @Async("asyncTaskExecutor")
    public void performNormalThreadTask() {
        Instant start = Instant.now();
        asyncTaskExecutor.execute(() -> {
            // 模拟耗时任务
            try {
                Thread.sleep(5000);
                System.out.println("普通线程任务完成!");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Instant end = Instant.now();
        long duration = Duration.between(start, end).toMillis();
        System.out.println("普通线程方法执行时间: " + duration + " 毫秒");
    }
}

控制器类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class VirtualThreadController {

    @Autowired
    private VirtualThreadService virtualThreadService;

    @GetMapping("/triggerVirtualThreadTask")
    public String triggerVirtualThreadTask() {
        virtualThreadService.performVirtualThreadTask();
        return "虚拟线程任务已触发!";
    }

    @GetMapping("/triggerNormalThreadTask")
    public String triggerNormalThreadTask() {
        virtualThreadService.performNormalThreadTask();
        return "普通线程任务已触发!";
    }
}

前端页面(index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>虚拟线程性能提升示例</title>
</head>
<body>
    <h1>虚拟线程性能提升示例</h1>
    <button onclick="triggerVirtualThreadTask()">触发虚拟线程任务</button>
    <button onclick="triggerNormalThreadTask()">触发普通线程任务</button>
    <button onclick="send10000Requests()">发送 10000 个请求</button>

    <script>
        function triggerVirtualThreadTask() {
            fetch('/triggerVirtualThreadTask')
      .then(response => response.text())
      .then(data => {
                    alert(data);
                })
      .catch(error => console.error('Error triggering virtual thread task:', error));
        }

        function triggerNormalThreadTask() {
            fetch('/triggerNormalThreadTask')
      .then(response => response.text())
      .then(data => {
                    alert(data);
                })
      .catch(error => console.error('Error triggering normal thread task:', error));
        }

        function send10000Requests() {
            for (let i = 0; i < 10000; i++) {
                fetch('/triggerVirtualThreadTask')
              .then(response => {
                    if (response.status === 200) {
                        console.log(`虚拟线程请求 ${i} 成功`);
                    } else {
                        console.error(`虚拟线程请求 ${i} 失败`);
                    }
                })
              .catch(error => console.error(`虚拟线程请求 ${i} 出错:`, error));

                fetch('/triggerNormalThreadTask')
              .then(response => {
                    if (response.status === 200) {
                        console.log(`普通线程请求 ${i} 成功`);
                    } else {
                        console.error(`普通线程请求 ${i} 失败`);
                    }
                })
              .catch(error => console.error(`普通线程请求 ${i} 出错:`, error));
            }
        }
    </script>
</body>
</html>

总结

通过以上的代码示例,在前端页面中增加了send10000Requests函数,用于异步发送 10000 个请求。在服务端的日志中可以比较两种线程执行的性能差异。根据实际的运行情况,可以对线程配置进行优化和调整,以达到更好的性能效果。

责任编辑:武晓燕 来源: 路条编程
相关推荐

2012-11-21 17:35:21

Oracle技术嘉年华

2014-11-11 15:57:07

2017-09-26 14:56:57

MongoDBLBS服务性能

2023-04-14 07:09:04

2018-06-26 15:23:34

华为云

2023-06-26 22:15:14

ChatGPT思维模型

2024-03-19 10:55:34

Spark

2021-04-19 05:44:18

显示器Twinkle Tra亮度调节

2018-11-19 09:47:04

人工智能芯片技术

2022-07-05 07:52:05

Kafka消费者性能

2016-07-28 10:03:03

Intel

2021-11-18 10:05:35

Java优化QPS

2022-05-31 10:51:12

架构技术优化

2023-05-31 07:24:48

2022-12-12 13:36:04

Python编译器

2015-03-12 10:21:05

阿里云宕机

2020-11-04 15:30:46

神经网络训练标签

2012-11-15 09:46:22

Xeon PhiIntel加速性能

2009-11-06 17:10:34

WCF服务性能计数器
点赞
收藏

51CTO技术栈公众号