spring boot 异步线程池的使用

  1. 创建Spring Boot项目

    首先,你需要创建一个Spring Boot项目。你可以使用Spring Initializr(https://start.spring.io/)来快速生成项目结构。

  2. 添加异步支持依赖

    在你的pom.xml文件中,确保你已经添加了Spring Boot的starter依赖,特别是spring-boot-starter-web,这将提供异步支持所需的依赖。

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  1. 配置异步线程池参数
    在Spring Boot中,你可以通过application.properties或application.yml文件来配置异步线程池的参数。以下是一个使用application.properties文件的示例:
properties 复制代码
# 异步线程池配置
async.executor.thread.core_pool_size=2
async.executor.thread.max_pool_size=10
async.executor.thread.queue_capacity=100
async.executor.thread.name.prefix=async-
async.executor.thread.keep_alive_seconds=60
async.executor.thread.await_termination_seconds=60

项目启动的时候线程池里面初始化两个线程,当两个线程都被占用了,又有新的任务进来先进入队列排队,达到队列的最大容量100,就会创建一个新的线程,只到达到最大数量10个,再有新的任务进来当前线程都不是空闲状态则会报错。

  1. 编写配置类以定义线程池
    接下来,你需要编写一个配置类,使用@Configuration注解来定义线程池。在这个配置类中,你将使用@Bean注解来创建一个ThreadPoolTaskExecutor实例,并根据application.properties中的配置来设置线程池的参数。
java 复制代码
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;

import java.util.concurrent.Executor;

@Configuration
@EnableAsync
public class AsyncConfig {

    @Value("${async.executor.thread.core_pool_size}")
    private int corePoolSize;

    @Value("${async.executor.thread.max_pool_size}")
    private int maxPoolSize;

    @Value("${async.executor.thread.queue_capacity}")
    private int queueCapacity;

    @Value("${async.executor.thread.name.prefix}")
    private String namePrefix;

    @Value("${async.executor.thread.keep_alive_seconds}")
    private int keepAliveSeconds;

    @Value("${async.executor.thread.await_termination_seconds}")
    private int awaitTerminationSeconds;

    @Bean(name = "taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(corePoolSize);
        // 设置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        // 设置队列容量
        executor.setQueueCapacity(queueCapacity);
        // 设置线程名称前缀
        executor.setThreadNamePrefix(namePrefix);
        // 线程空闲时的存活时间
        executor.setKeepAliveSeconds(keepAliveSeconds);
        // 关闭线程池等待任务完成的最长时间
        executor.setAwaitTerminationSeconds(awaitTerminationSeconds);
        // 关闭线程池等待已提交线程执行完毕
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 异常策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
  1. 编写异步任务类
    现在,你可以编写一个包含异步方法的类。在这个类中,你将使用@Async注解来标记需要异步执行的方法,并指定前面定义的线程池(在这个例子中是taskExecutor)。
java 复制代码
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {

    // 在需要使用异步处理的方法上添加注解
    @Async("taskExecutor")
    public void executeAsyncTask() {
        System.out.println("执行异步任务 - " + Thread.currentThread().getName());
        try {
            // 模拟长时间运行的任务
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
  1. 最后,在你的控制器或其他服务类中,你可以调用这个异步方法来执行异步任务。
java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;

    @GetMapping("/async")
    public String handleAsyncRequest() {
        asyncService.executeAsyncTask();
        return "异步任务已启动";
    }
}

通过以上步骤,你就成功地在Spring Boot中配置了异步线程池,并编写了一个异步任务类来演示如何使用它。这样,你就可以在需要时轻松地将任务交给线程池异步执行了。

注意:

@Async注解不生效

‌从Spring容器管理的bean中调用‌:@Async注解的方法必须是从Spring容器管理的bean中调用的。如果从一个非Spring管理的类中调用,那么异步效果将不会生效。

‌自调用问题‌:同一个类中的方法调用不会被Spring的AOP代理捕获,因此如果在一个类中调用同一个类的另一个@Async方法,那么异步效果也不会生效。为了避免这个问题,可以将异步方法移动到另一个bean中,并通过依赖注入来调用。

相关推荐
极光代码工作室2 小时前
基于SpringBoot的课程预约系统
java·springboot·web开发·后端开发
Leighteen2 小时前
`try-finally` 里的 `return`:为什么 `finally` 会悄悄改掉返回值、吞掉异常
java·开发语言
名字还没想好☜3 小时前
Go 的 time.After 在 select 循环里内存泄漏:定时器堆积原理与 timer.Reset 正确姿势
java·数据库·golang·go·goroutine
圆山猫3 小时前
[Virtualization](三):RISC-V H-extension 与 Guest 执行模式
android·java·risc-v
caishenzhibiao3 小时前
期货先行者主图 同花顺期货通指标
java·c语言·c#
史呆芬4 小时前
分布式事务实战:微服务跨服务数据一致性解决方案
java·后端·spring cloud
IT界的老黄牛4 小时前
限流命中后该怎么办:直接丢、阻塞等待、延迟重投三种姿势的取舍
java·rocketmq·redisson·令牌桶·削峰·分布式限流
daad7775 小时前
记录matlab状态机demo
java·网络·matlab
牡丹雅忻15 小时前
AES 加密模式演进:从 ECB、CBC 到 GCM 的 C# 深度实践
java·开发语言·c#
paopaokaka_luck5 小时前
基于springboot3+vue3的智能文库平台(AI智能搜索、AI智能汇总、实时在线状态展示、多格式文档预览与富文本编辑、Echarts图形化分析)
前端·网络·spring boot·网络协议·echarts