成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

使用 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亮度調節

2022-07-05 07:52:05

Kafka消費者性能

2018-11-19 09:47:04

人工智能芯片技術

2016-07-28 10:03:03

Intel

2021-11-18 10:05:35

Java優化QPS

2023-05-31 07:24:48

2015-03-12 10:21:05

阿里云宕機

2022-12-12 13:36:04

Python編譯器

2022-05-31 10:51:12

架構技術優化

2020-11-04 15:30:46

神經網絡訓練標簽

2012-11-15 09:46:22

Xeon PhiIntel加速性能

2022-05-26 08:12:39

PandasApply技巧

2013-09-23 10:03:29

擬態計算機能效
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 波多野结衣一区二区三区在线观看 | 午夜在线精品 | 欧美精品在线播放 | 国产一区二区三区四区在线观看 | 一区二区在线 | 国产欧美精品在线 | 国产美女黄色 | 国产精品99久 | 日韩国产一区二区 | 日韩精品在线视频 | 亚洲黄色av| 欧美在线a | jizz在线看片 | 国产精品毛片 | 欧美一级二级视频 | 黄色在线免费观看视频 | 91精品国产综合久久久密闭 | 国产高清视频一区 | 美女天天操| 欧美日韩一区二区在线观看 | 亚洲一区二区三区四区五区中文 | 天天操天天干天天曰 | 日韩高清一区 | 91精品国产综合久久精品 | 一级做a爰片性色毛片视频停止 | 91免费视频观看 | 观看av| 奇米超碰 | 亚洲第一色av | 亚洲视频在线免费观看 | 在线不卡av | 国产男女精品 | 99综合| 精品一区二区久久久久久久网精 | 亚洲国产成人精品久久久国产成人一区 | 国产中文字幕亚洲 | 日本一区二区视频 | 91视频官网 | av av在线| 成人免费日韩 | 国产精品久久久久久久久久 |