Spring Boot利用@Async异步调用:ThreadPoolTaskScheduler线程池的优雅关闭详解
前言
之前分享了一篇关于spring boot中使用@async来实现异步任务和线程池控制的文章:《spring boot使用@async实现异步调用:自定义线程池》。由于最近身边也发现了不少异步任务没有正确处理而导致的不少问题,所以在本文就接前面内容,继续说说线程池的优雅关闭,主要针对threadpooltaskscheduler线程池。
问题现象
在上篇文章的例子chapter4-1-3中,我们定义了一个线程池,然后利用@async注解写了3个任务,并指定了这些任务执行使用的线程池。在上文的单元测试中,我们没有具体说说shutdown相关的问题,下面我们就来模拟一个问题现场出来。
第一步:如前文一样,我们定义一个threadpooltaskscheduler线程池:
@springbootapplication public class application { public static void main(string[] args) { springapplication.run(application.class, args); } @enableasync @configuration class taskpoolconfig { @bean("taskexecutor") public executor taskexecutor() { threadpooltaskscheduler executor = new threadpooltaskscheduler(); executor.setpoolsize(20); executor.setthreadnameprefix("taskexecutor-"); return executor; } } }
第二步:改造之前的异步任务,让它依赖一个外部资源,比如:redis
@slf4j @component public class task { @autowired private stringredistemplate stringredistemplate; @async("taskexecutor") public void dotaskone() throws exception { log.info("开始做任务一"); long start = system.currenttimemillis(); log.info(stringredistemplate.randomkey()); long end = system.currenttimemillis(); log.info("完成任务一,耗时:" + (end - start) + "毫秒"); } @async("taskexecutor") public void dotasktwo() throws exception { log.info("开始做任务二"); long start = system.currenttimemillis(); log.info(stringredistemplate.randomkey()); long end = system.currenttimemillis(); log.info("完成任务二,耗时:" + (end - start) + "毫秒"); } @async("taskexecutor") public void dotaskthree() throws exception { log.info("开始做任务三"); long start = system.currenttimemillis(); log.info(stringredistemplate.randomkey()); long end = system.currenttimemillis(); log.info("完成任务三,耗时:" + (end - start) + "毫秒"); } }
注意:这里省略了pom.xml中引入依赖和配置redis的步骤
第三步:修改单元测试,模拟高并发情况下shutdown的情况:
@runwith(springjunit4classrunner.class) @springboottest public class applicationtests { @autowired private task task; @test @sneakythrows public void test() { for (int i = 0; i < 10000; i++) { task.dotaskone(); task.dotasktwo(); task.dotaskthree(); if (i == 9999) { system.exit(0); } } } }
说明:通过for循环往上面定义的线程池中提交任务,由于是异步执行,在执行过程中,利用system.exit(0)来关闭程序,此时由于有任务在执行,就可以观察这些异步任务的销毁与spring容器中其他资源的顺序是否安全。
第四步:运行上面的单元测试,我们将碰到下面的异常内容。
org.springframework.data.redis.redisconnectionfailureexception: cannot get jedis connection; nested exception is redis.clients.jedis.exceptions.jedisconnectionexception: could not get a resource from the pool at org.springframework.data.redis.connection.jedis.jedisconnectionfactory.fetchjedisconnector(jedisconnectionfactory.java:204) ~[spring-data-redis-1.8.10.release.jar:na] at org.springframework.data.redis.connection.jedis.jedisconnectionfactory.getconnection(jedisconnectionfactory.java:348) ~[spring-data-redis-1.8.10.release.jar:na] at org.springframework.data.redis.core.redisconnectionutils.dogetconnection(redisconnectionutils.java:129) ~[spring-data-redis-1.8.10.release.jar:na] at org.springframework.data.redis.core.redisconnectionutils.getconnection(redisconnectionutils.java:92) ~[spring-data-redis-1.8.10.release.jar:na] at org.springframework.data.redis.core.redisconnectionutils.getconnection(redisconnectionutils.java:79) ~[spring-data-redis-1.8.10.release.jar:na] at org.springframework.data.redis.core.redistemplate.execute(redistemplate.java:194) ~[spring-data-redis-1.8.10.release.jar:na] at org.springframework.data.redis.core.redistemplate.execute(redistemplate.java:169) ~[spring-data-redis-1.8.10.release.jar:na] at org.springframework.data.redis.core.redistemplate.randomkey(redistemplate.java:781) ~[spring-data-redis-1.8.10.release.jar:na] at com.didispace.async.task.dotaskone(task.java:26) ~[classes/:na] at com.didispace.async.task$$fastclassbyspringcglib$$ca3ff9d6.invoke(<generated>) ~[classes/:na] at org.springframework.cglib.proxy.methodproxy.invoke(methodproxy.java:204) ~[spring-core-4.3.14.release.jar:4.3.14.release] at org.springframework.aop.framework.cglibaopproxy$cglibmethodinvocation.invokejoinpoint(cglibaopproxy.java:738) ~[spring-aop-4.3.14.release.jar:4.3.14.release] at org.springframework.aop.framework.reflectivemethodinvocation.proceed(reflectivemethodinvocation.java:157) ~[spring-aop-4.3.14.release.jar:4.3.14.release] at org.springframework.aop.interceptor.asyncexecutioninterceptor$1.call(asyncexecutioninterceptor.java:115) ~[spring-aop-4.3.14.release.jar:4.3.14.release] at java.util.concurrent.futuretask.run(futuretask.java:266) [na:1.8.0_151] at java.util.concurrent.scheduledthreadpoolexecutor$scheduledfuturetask.access$201(scheduledthreadpoolexecutor.java:180) [na:1.8.0_151] at java.util.concurrent.scheduledthreadpoolexecutor$scheduledfuturetask.run(scheduledthreadpoolexecutor.java:293) [na:1.8.0_151] at java.util.concurrent.threadpoolexecutor.runworker(threadpoolexecutor.java:1149) [na:1.8.0_151] at java.util.concurrent.threadpoolexecutor$worker.run(threadpoolexecutor.java:624) [na:1.8.0_151] at java.lang.thread.run(thread.java:748) [na:1.8.0_151] caused by: redis.clients.jedis.exceptions.jedisconnectionexception: could not get a resource from the pool at redis.clients.util.pool.getresource(pool.java:53) ~[jedis-2.9.0.jar:na] at redis.clients.jedis.jedispool.getresource(jedispool.java:226) ~[jedis-2.9.0.jar:na] at redis.clients.jedis.jedispool.getresource(jedispool.java:16) ~[jedis-2.9.0.jar:na] at org.springframework.data.redis.connection.jedis.jedisconnectionfactory.fetchjedisconnector(jedisconnectionfactory.java:194) ~[spring-data-redis-1.8.10.release.jar:na] ... 19 common frames omitted caused by: java.lang.interruptedexception: null at java.util.concurrent.locks.abstractqueuedsynchronizer$conditionobject.reportinterruptafterwait(abstractqueuedsynchronizer.java:2014) ~[na:1.8.0_151] at java.util.concurrent.locks.abstractqueuedsynchronizer$conditionobject.awaitnanos(abstractqueuedsynchronizer.java:2088) ~[na:1.8.0_151] at org.apache.commons.pool2.impl.linkedblockingdeque.pollfirst(linkedblockingdeque.java:635) ~[commons-pool2-2.4.3.jar:2.4.3] at org.apache.commons.pool2.impl.genericobjectpool.borrowobject(genericobjectpool.java:442) ~[commons-pool2-2.4.3.jar:2.4.3] at org.apache.commons.pool2.impl.genericobjectpool.borrowobject(genericobjectpool.java:361) ~[commons-pool2-2.4.3.jar:2.4.3] at redis.clients.util.pool.getresource(pool.java:49) ~[jedis-2.9.0.jar:na] ... 22 common frames omitted
如何解决
原因分析
从异常信息jedisconnectionexception: could not get a resource from the pool
来看,我们很容易的可以想到,在应用关闭的时候异步任务还在执行,由于redis连接池先销毁了,导致异步任务中要访问redis的操作就报了上面的错。所以,我们得出结论,上面的实现方式在应用关闭的时候是不优雅的,那么我们要怎么做呢?
解决方法
要解决上面的问题很简单,spring的threadpooltaskscheduler为我们提供了相关的配置,只需要加入如下设置即可:
@bean("taskexecutor") public executor taskexecutor() { threadpooltaskscheduler executor = new threadpooltaskscheduler(); executor.setpoolsize(20); executor.setthreadnameprefix("taskexecutor-"); executor.setwaitfortaskstocompleteonshutdown(true); executor.setawaitterminationseconds(60); return executor; }
说明:setwaitfortaskstocompleteonshutdown(true)
该方法就是这里的关键,用来设置线程池关闭的时候等待所有任务都完成再继续销毁其他的bean,这样这些异步任务的销毁就会先于redis线程池的销毁。同时,这里还设置了setawaitterminationseconds(60),该方法用来设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以确保应用最后能够被关闭,而不是阻塞住。
完整示例:
读者可以根据喜好选择下面的两个仓库中查看chapter4-1-4项目:
github:https://github.com/dyc87112/springboot-learning/
gitee:https://gitee.com/didispace/springboot-learning/
本地下载:http://xiazai.jb51.net/201805/yuanma/springboot-learning(jb51.net).rar
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。