SpringBoot 整合线程池

技术·Java · 今天 · 1 人浏览

步骤如下:

1. 启动类加入 @EnableAsync 注解

@SpringBootApplication
@EnableAsync
public class FacadeH5Application {
    public static void main(String[] args) {
        SpringApplication.run(FacadeH5Application.class, args);
    }
}

2. 在方法上加 @Async 注解

@Async
public void m1() {
    //do something
}

3. 创建线程池配置文件

# 核心线程数
spring.task.execution.pool.core-size=8  
# 最大线程数
spring.task.execution.pool.max-size=16
# 空闲线程存活时间
spring.task.execution.pool.keep-alive=60s
# 是否允许核心线程超时
spring.task.execution.pool.allow-core-thread-timeout=true
# 线程队列数量
spring.task.execution.pool.queue-capacity=100
# 线程关闭等待
spring.task.execution.shutdown.await-termination=false
spring.task.execution.shutdown.await-termination-period=
# 线程名称前缀
spring.task.execution.thread-name-prefix=task-
@Configuration
public class ThreadPoolConfig {
    @Bean
    public TaskExecutor taskExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //设置核心线程数
        executor.setCorePoolSize(10);
        //设置最大线程数
        executor.setMaxPoolSize(20);
        //设置队列容量
        executor.setQueueCapacity(20);
        //设置线程活跃时间
        executor.setKeepAliveSeconds(30);
        //设置线程名称前缀
        executor.setThreadNamePrefix("sendSms-");
        //设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //设置线程池中任务的等待时间
        executor.setAwaitTerminationSeconds(60);

        return executor;
    }
}

配置多个线程池

@Configuration
public class ThreadPoolConfig {
    @Bean("ThreadPool1")
    public TaskExecutor taskExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        ......
        return executor;
    }
    @Bean("ThreadPool2")
    public TaskExecutor taskExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        ......
        return executor;
    }
}

在使用 @Async 注解时就需要指定具体的线程池

@Async("ThreadPool1")
public void m1() {
    //do something
}
Jason
Jason 注销
Theme Jasmine