Springboot的异步线程池图鉴

Posted 玲珑塔

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springboot的异步线程池图鉴相关的知识,希望对你有一定的参考价值。

1:定义线程池

技术图片
@EnableAsync
    @Configuration
    class TaskPoolConfig {
 
        @Bean("taskExecutor")
        public Executor taskExecutor() {
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            executor.setCorePoolSize(10);
            executor.setMaxPoolSize(20);
            executor.setQueueCapacity(200);
            executor.setKeepAliveSeconds(60);
            executor.setThreadNamePrefix("taskExecutor-");
            executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setWaitForTasksToCompleteOnShutdown(true);
         executor.setAwaitTerminationSeconds(60);
 return executor;
    }
}
View Code

2:如何使用该线程池呢?

技术图片
@Slf4j
@Component
public class Task {
 
    public static Random random = new Random();
@Autowired
    private StringRedisTemplate stringRedisTemplate;
@Async("taskExecutor")
    public void doTaskOne() throws Exception {
        log.info("开始做任务一");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();        log.info(stringRedisTemplate.randomKey());
        log.info("完成任务一,耗时:" + (end - start) + "毫秒");
    }
 
    @Async("taskExecutor")
    public void doTaskTwo() throws Exception {
        log.info("开始做任务二");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        log.info("完成任务二,耗时:" + (end - start) + "毫秒");
    }
 
    @Async("taskExecutor")
    public void doTaskThree() throws Exception {
        log.info("开始做任务三");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        log.info("完成任务三,耗时:" + (end - start) + "毫秒");
    }
 
}
View Code

3 执行异步任务

技术图片
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class ApplicationTests {
 
    @Autowired
    private Task task;
 
    @Test
    public void test() throws Exception {
 
        task.doTaskOne();
        task.doTaskTwo();
        task.doTaskThree();
 
        Thread.currentThread().join();
    }
 
}
View Code

4 打印结果

技术图片
2018-03-27 22:01:15.620  INFO 73703 --- [ taskExecutor-1] com.didispace.async.Task  : 开始做任务一

2018-03-27 22:01:15.620  INFO 73703 --- [ taskExecutor-2] com.didispace.async.Task  : 开始做任务二
2018-03-27 22:01:15.620  INFO 73703 --- [ taskExecutor-3] com.didispace.async.Task  : 开始做任务三
2018-03-27 22:01:18.165  INFO 73703 --- [ taskExecutor-2] com.didispace.async.Task  : 完成任务二,耗时:2545毫秒
2018-03-27 22:01:22.149  INFO 73703 --- [ taskExecutor-3] com.didispace.async.Task  : 完成任务三,耗时:6529毫秒
2018-03-27 22:01:23.912  INFO 73703 --- [ taskExecutor-1] com.didispace.async.Task  : 完成任务一,耗时:8292毫秒
View Code

5 注意事项

注: @Async所修饰的函数不要定义为static类型,这样异步调用不会生效

从异常信息JedisConnectionException: Could not get a resource from the pool来看,我们很容易的可以想到,在应用关闭的时候异步任务还在执行,由于Redis连接池先销毁了,导致异步任务中要访问Redis的操作就报了上面的错。所以,我们得出结论,上面的实现方式在应用关闭的时候是不优雅的,那么我们要怎么做呢?如下设置:

executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);

以上是关于Springboot的异步线程池图鉴的主要内容,如果未能解决你的问题,请参考以下文章

线程池,springboot工程中的异步

#yyds干货盘点# springboot配置@Async异步任务的线程池

SpringBoot自定义异步任务线程池

SpringBoot-技术专区-实战方案-应用监控线程池

Springboot的异步线程池

2020之最专业的并发编程篇:知识图鉴+知识点剖析+高频面试+书籍