Spring Boot 中多线程工具类的配置与使用:基于 YAML 配置文件

news/2025/2/24 2:05:23/

文章目录

      • Spring Boot 中多线程工具类的配置与使用:基于 YAML 配置文件
      • 1. 为什么需要多线程工具类?
      • 2. 实现步骤
        • 2.1 添加依赖
        • 2.2 配置线程池参数
        • 2.3 创建配置类
        • 2.4 创建线程池工具类
        • 2.5 使用线程池工具类
        • 2.6 测试线程池工具类
      • 3. 配置文件的灵活性
      • 4. 总结


Spring Boot 中多线程工具类的配置与使用:基于 YAML 配置文件

在现代软件开发中,多线程编程是提高系统性能和并发处理能力的重要手段。Spring Boot 作为一款流行的 Java 开发框架,提供了强大的多线程支持。本文将详细介绍如何在 Spring Boot 中结合 YAML 配置文件,实现一个灵活、可配置的多线程工具类。


1. 为什么需要多线程工具类?

在多线程编程中,直接使用 ThreadExecutorService 可能会导致以下问题:

  • 资源浪费:频繁创建和销毁线程会消耗大量系统资源。
  • 难以管理:线程的生命周期和状态难以监控和维护。
  • 配置不灵活:线程池的参数(如核心线程数、队列容量等)硬编码在代码中,难以动态调整。

通过封装一个多线程工具类,并结合 YAML 配置文件,可以解决上述问题,使多线程编程更加高效和灵活。


2. 实现步骤

2.1 添加依赖

pom.xml 中添加 Spring Boot 的依赖:

<dependencies><!-- Spring Boot Starter --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><!-- Spring Boot Configuration Processor --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency>
</dependencies>
2.2 配置线程池参数

application.yml 中定义线程池的配置参数:

thread-pool:core-pool-size: 10 # 核心线程数max-pool-size: 20 # 最大线程数queue-capacity: 100 # 任务队列容量keep-alive-time: 60 # 线程空闲时间(秒)thread-name-prefix: "custom-thread-" # 线程名称前缀
2.3 创建配置类

通过 @ConfigurationProperties 注解将 YAML 文件中的配置映射到 Java 类中:

java">import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;@Component
@ConfigurationProperties(prefix = "thread-pool")
public class ThreadPoolProperties {private int corePoolSize;private int maxPoolSize;private int queueCapacity;private long keepAliveTime;private String threadNamePrefix;// Getters and Setterspublic int getCorePoolSize() {return corePoolSize;}public void setCorePoolSize(int corePoolSize) {this.corePoolSize = corePoolSize;}public int getMaxPoolSize() {return maxPoolSize;}public void setMaxPoolSize(int maxPoolSize) {this.maxPoolSize = maxPoolSize;}public int getQueueCapacity() {return queueCapacity;}public void setQueueCapacity(int queueCapacity) {this.queueCapacity = queueCapacity;}public long getKeepAliveTime() {return keepAliveTime;}public void setKeepAliveTime(long keepAliveTime) {this.keepAliveTime = keepAliveTime;}public String getThreadNamePrefix() {return threadNamePrefix;}public void setThreadNamePrefix(String threadNamePrefix) {this.threadNamePrefix = threadNamePrefix;}
}
2.4 创建线程池工具类

在工具类中注入 ThreadPoolProperties,并根据配置创建线程池:

java">import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.*;@Component
public class ThreadPoolUtil {private ThreadPoolExecutor threadPool;@Autowiredprivate ThreadPoolProperties threadPoolProperties;/*** 初始化线程池*/@PostConstructpublic void init() {threadPool = new ThreadPoolExecutor(threadPoolProperties.getCorePoolSize(),threadPoolProperties.getMaxPoolSize(),threadPoolProperties.getKeepAliveTime(),TimeUnit.SECONDS,new LinkedBlockingQueue<>(threadPoolProperties.getQueueCapacity()),new ThreadFactory() {private final AtomicInteger threadNumber = new AtomicInteger(1);@Overridepublic Thread newThread(Runnable r) {return new Thread(r, threadPoolProperties.getThreadNamePrefix() + threadNumber.getAndIncrement());}},new ThreadPoolExecutor.AbortPolicy() // 拒绝策略:直接抛出异常);}/*** 提交任务(Runnable)** @param task 任务*/public void execute(Runnable task) {threadPool.execute(task);}/*** 提交任务(Callable)** @param task 任务* @param <T>  返回值类型* @return Future 对象*/public <T> Future<T> submit(Callable<T> task) {return threadPool.submit(task);}/*** 关闭线程池(等待所有任务完成)*/@PreDestroypublic void shutdown() {if (threadPool != null) {threadPool.shutdown();try {if (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) {threadPool.shutdownNow();}} catch (InterruptedException e) {threadPool.shutdownNow();Thread.currentThread().interrupt();}}}/*** 获取线程池状态** @return 线程池状态信息*/public String getThreadPoolStatus() {if (threadPool == null) {return "Thread pool is not initialized.";}return String.format("Pool Status: [CorePoolSize: %d, ActiveThreads: %d, CompletedTasks: %d, QueueSize: %d]",threadPool.getCorePoolSize(),threadPool.getActiveCount(),threadPool.getCompletedTaskCount(),threadPool.getQueue().size());}
}
2.5 使用线程池工具类

在业务代码中注入 ThreadPoolUtil,并提交任务:

java">import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class TaskService {@Autowiredprivate ThreadPoolUtil threadPoolUtil;public void runTask() {// 提交 Runnable 任务threadPoolUtil.execute(() -> {System.out.println("Runnable task is running.");});// 提交 Callable 任务并获取结果Future<String> future = threadPoolUtil.submit(() -> {Thread.sleep(1000);return "Callable task result";});try {System.out.println("Callable task result: " + future.get());} catch (InterruptedException | ExecutionException e) {e.printStackTrace();}// 打印线程池状态System.out.println(threadPoolUtil.getThreadPoolStatus());}
}
2.6 测试线程池工具类

编写单元测试,验证线程池的功能:

java">import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
public class ThreadPoolUtilTest {@Autowiredprivate TaskService taskService;@Testpublic void testThreadPool() {taskService.runTask();}
}

3. 配置文件的灵活性

通过 application.yml 配置文件,可以灵活调整线程池的参数,而无需修改代码。例如:

  • 调整核心线程数:

    thread-pool:core-pool-size: 20
    
  • 调整任务队列容量:

    thread-pool:queue-capacity: 200
    
  • 调整线程名称前缀:

    thread-pool:thread-name-prefix: "app-thread-"
    

4. 总结

通过将线程池的配置参数提取到 application.yml 中,并结合 Spring Boot 的依赖注入机制,我们可以实现一个灵活、可配置的多线程工具类。这种方式不仅提高了代码的可维护性,还能根据实际需求动态调整线程池的行为,是 Spring Boot 项目中管理多线程任务的推荐做法。希望本文能帮助你更好地理解和应用 Spring Boot 中的多线程编程技术!


http://www.ppmy.cn/news/1574524.html

相关文章

低空经济应用场景细分赛道探索,无人机开源飞控二次开发详解

低空经济应用场景细分赛道探索 低空经济作为一个新兴的经济形态&#xff0c;随着直升机、eVTOL&#xff08;电动垂直起降飞行器&#xff09;、无人机等新技术新产品的快速发展&#xff0c;其应用范围正向第一、第二、第三产业中的多个领域迅速拓展。以下是对低空经济应用场景细…

蓝桥杯 Java B 组之岛屿数量、二叉树路径和(区分DFS与回溯)

Day 3&#xff1a;岛屿数量、二叉树路径和&#xff08;区分DFS与回溯&#xff09; &#x1f4d6; 一、深度优先搜索&#xff08;DFS&#xff09;简介 深度优先搜索&#xff08;Depth-First Search&#xff0c;DFS&#xff09;是一种用于遍历或搜索树或图的算法。它会沿着树的分…

【洛谷排序算法】P1012拼数-详细讲解

洛谷 P1012 拼数这道题本身并非单纯考察某种经典排序算法&#xff08;如冒泡排序、选择排序、插入排序、快速排序、归并排序等&#xff09;的实现&#xff0c;而是在排序的基础上&#xff0c;自定义了排序的比较规则&#xff0c;属于自定义排序类型的题目。不过它借助了标准库中…

安装Bash completion解决tab不能补全问题

Bash completion 是一个强大的功能&#xff0c;它可以帮助你在 Bash shell 中自动补全命令、文件名、选项等。默认情况下&#xff0c;Bash completion 应该在所有用户&#xff08;包括 root 用户&#xff09;下都能工作。不过&#xff0c;如果你发现 root 用户下没有启用 Bash …

【C++游戏开发-五子棋】

使用C开发五子棋游戏的详细实现方案&#xff0c;涵盖核心逻辑、界面设计和AI对战功能&#xff1a; 1. 项目结构 FiveChess/ ├── include/ │ ├── Board.h // 棋盘类 │ ├── Player.h // 玩家类 │ ├── AI.h // AI类 │ └── Game.h // 游戏主逻辑 ├── src/ …

BS架构网络安全 网络安全架构分析

文章目录 Web架构安全分析 一、web工作机制 1. 简述用户访问一个网站的完整路径2. web系统结构 二、url 1. 概述2. 完整格式3. url编码 三、HTTP 1. request请求报文2. http请求方法3. response响应报文 三、同源策略 1. 概述2. 同源策略的条件3. 非同源受到的限制4. …

HarmonyOS 应用下载网络文件保存到本地公共目录

在日常开发中&#xff0c;文件下载是一个非常常见的业务场景。无论是从远程服务器获取资源&#xff0c;还是将用户生成的内容保存到本地&#xff0c;文件下载功能都是不可或缺的。本文将详细介绍如何实现文件下载功能&#xff0c;并深入解析相关的API使用方法&#xff0c;帮助开…

CH340N的使用注意事项

使用 CH340N 将 MCU 的串口&#xff08;UART&#xff09;转换为 USB 输出是一种常见的方案&#xff0c;适用于需要将嵌入式设备连接到电脑的场景。以下是详细的连接方法和步骤&#xff1a; 1. CH340N 简介 功能&#xff1a;CH340N 是一款 USB 转串口芯片&#xff0c;支持 USB …