spring boot 项目创建和使用线程池

  • Post author:
  • Post category:其他




项目使用线程池实例

创建 ExecutorConfig 类,

@Configuration
@EnableAsync // 开启异步任务支持
public class ExecutorConfig {

    @Resource
    private Environment env;

    //创建线程池
    @Bean("taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        pool.setThreadNamePrefix("--------------全局线程池-----------------");
        pool.setCorePoolSize(Integer.parseInt(env.getProperty("threadpool.corePoolSize")));
        pool.setMaxPoolSize(Integer.parseInt(env.getProperty("threadpool.maxPoolSize")));
        pool.setKeepAliveSeconds(Integer.parseInt(env.getProperty("threadpool.queueCapacity")));
        pool.setQueueCapacity(Integer.parseInt(env.getProperty("threadpool.keepAliveSeconds")));
        // 直接在execute方法的调用线程中运行
        pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化
        pool.initialize();
        return pool;
    }

}

直接在需要获取线程的方法上面加上该注解,在调用此方法时就会自动获取线程池的线程执行任务:

	@Override
    @Async("taskExecutor")
    public Object generatePdf(String id) {
        Asserts.isTrue(!StringUtils.isEmpty(id), "id不能为空");
        ...
    }    
        

线程池的相关参数在配置文件中配置:

threadpool:
  corePoolSize: 8
  maxPoolSize: 16
  queueCapacity: 60
  keepAliveSeconds: 300



版权声明:本文为weixin_44340643原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。