Spring Boot利用@Async異步調(diào)用:ThreadPoolTaskScheduler線程池的優(yōu)雅關(guān)閉詳解
前言
之前分享了一篇關(guān)于Spring Boot中使用@Async來(lái)實(shí)現(xiàn)異步任務(wù)和線程池控制的文章:《Spring Boot使用@Async實(shí)現(xiàn)異步調(diào)用:自定義線程池》。由于最近身邊也發(fā)現(xiàn)了不少異步任務(wù)沒(méi)有正確處理而導(dǎo)致的不少問(wèn)題,所以在本文就接前面內(nèi)容,繼續(xù)說(shuō)說(shuō)線程池的優(yōu)雅關(guān)閉,主要針對(duì)ThreadPoolTaskScheduler線程池。
問(wèn)題現(xiàn)象
在上篇文章的例子Chapter4-1-3中,我們定義了一個(gè)線程池,然后利用@Async注解寫了3個(gè)任務(wù),并指定了這些任務(wù)執(zhí)行使用的線程池。在上文的單元測(cè)試中,我們沒(méi)有具體說(shuō)說(shuō)shutdown相關(guān)的問(wèn)題,下面我們就來(lái)模擬一個(gè)問(wèn)題現(xiàn)場(chǎng)出來(lái)。
第一步:如前文一樣,我們定義一個(gè)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;
}
}
}
第二步:改造之前的異步任務(wù),讓它依賴一個(gè)外部資源,比如:Redis
@Slf4j
@Component
public class Task {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Async("taskExecutor")
public void doTaskOne() throws Exception {
log.info("開始做任務(wù)一");
long start = System.currentTimeMillis();
log.info(stringRedisTemplate.randomKey());
long end = System.currentTimeMillis();
log.info("完成任務(wù)一,耗時(shí):" + (end - start) + "毫秒");
}
@Async("taskExecutor")
public void doTaskTwo() throws Exception {
log.info("開始做任務(wù)二");
long start = System.currentTimeMillis();
log.info(stringRedisTemplate.randomKey());
long end = System.currentTimeMillis();
log.info("完成任務(wù)二,耗時(shí):" + (end - start) + "毫秒");
}
@Async("taskExecutor")
public void doTaskThree() throws Exception {
log.info("開始做任務(wù)三");
long start = System.currentTimeMillis();
log.info(stringRedisTemplate.randomKey());
long end = System.currentTimeMillis();
log.info("完成任務(wù)三,耗時(shí):" + (end - start) + "毫秒");
}
}
注意:這里省略了pom.xml中引入依賴和配置redis的步驟
第三步:修改單元測(cè)試,模擬高并發(fā)情況下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);
}
}
}
}
說(shuō)明:通過(guò)for循環(huán)往上面定義的線程池中提交任務(wù),由于是異步執(zhí)行,在執(zhí)行過(guò)程中,利用System.exit(0)來(lái)關(guān)閉程序,此時(shí)由于有任務(wù)在執(zhí)行,就可以觀察這些異步任務(wù)的銷毀與Spring容器中其他資源的順序是否安全。
第四步:運(yùn)行上面的單元測(cè)試,我們將碰到下面的異常內(nèi)容。
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來(lái)看,我們很容易的可以想到,在應(yīng)用關(guān)閉的時(shí)候異步任務(wù)還在執(zhí)行,由于Redis連接池先銷毀了,導(dǎo)致異步任務(wù)中要訪問(wèn)Redis的操作就報(bào)了上面的錯(cuò)。所以,我們得出結(jié)論,上面的實(shí)現(xiàn)方式在應(yīng)用關(guān)閉的時(shí)候是不優(yōu)雅的,那么我們要怎么做呢?
解決方法
要解決上面的問(wèn)題很簡(jiǎn)單,Spring的ThreadPoolTaskScheduler為我們提供了相關(guān)的配置,只需要加入如下設(shè)置即可:
@Bean("taskExecutor")
public Executor taskExecutor() {
ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
executor.setPoolSize(20);
executor.setThreadNamePrefix("taskExecutor-");
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
return executor;
}
說(shuō)明:setWaitForTasksToCompleteOnShutdown(true)該方法就是這里的關(guān)鍵,用來(lái)設(shè)置線程池關(guān)閉的時(shí)候等待所有任務(wù)都完成再繼續(xù)銷毀其他的Bean,這樣這些異步任務(wù)的銷毀就會(huì)先于Redis線程池的銷毀。同時(shí),這里還設(shè)置了setAwaitTerminationSeconds(60),該方法用來(lái)設(shè)置線程池中任務(wù)的等待時(shí)間,如果超過(guò)這個(gè)時(shí)候還沒(méi)有銷毀就強(qiáng)制銷毀,以確保應(yīng)用最后能夠被關(guān)閉,而不是阻塞住。
完整示例:
讀者可以根據(jù)喜好選擇下面的兩個(gè)倉(cāng)庫(kù)中查看Chapter4-1-4項(xiàng)目:
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
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
- springboot定時(shí)任務(wù)@Scheduled執(zhí)行多次的問(wèn)題
- SpringBoot執(zhí)行定時(shí)任務(wù)@Scheduled的方法
- Spring boot如何通過(guò)@Scheduled實(shí)現(xiàn)定時(shí)任務(wù)及多線程配置
- spring-boot通過(guò)@Scheduled配置定時(shí)任務(wù)及定時(shí)任務(wù)@Scheduled注解的方法
- 詳解Spring Boot中使用@Scheduled創(chuàng)建定時(shí)任務(wù)
- spring?boot?使用?@Scheduled?注解和?TaskScheduler?接口實(shí)現(xiàn)定時(shí)任務(wù)
相關(guān)文章
java數(shù)據(jù)結(jié)構(gòu)關(guān)于棧的實(shí)例應(yīng)用
大家好,本篇文章主要講的是java數(shù)據(jù)結(jié)構(gòu)關(guān)于棧的實(shí)例應(yīng)用,感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏一下,方便下次瀏覽2021-12-12
SpringBoot3.x版本與Mybatis-Plus不兼容問(wèn)題
當(dāng)使用3.x版本的SpringBoot結(jié)合Mybatis-Plus時(shí)版本不兼容就會(huì)報(bào)錯(cuò),本文就來(lái)介紹一下這個(gè)問(wèn)題的解決方法,感興趣的可以了解一下2024-03-03
springboot 接口返回字符串帶引號(hào)的問(wèn)題解決
本文主要介紹了springboot 接口返回字符串帶引號(hào)的問(wèn)題解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
SpringBoot與velocity的結(jié)合的示例代碼
本篇文章主要介紹了SpringBoot與velocity的結(jié)合的示例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-03-03
SpringBoot中GlobalExceptionHandler異常處理機(jī)制詳細(xì)說(shuō)明
Spring Boot的GlobalExceptionHandler是一個(gè)全局異常處理器,用于捕獲和處理應(yīng)用程序中發(fā)生的所有異常,這篇文章主要給大家介紹了關(guān)于Java中GlobalExceptionHandler異常處理機(jī)制的相關(guān)資料,需要的朋友可以參考下2024-03-03
spring boot異步(Async)任務(wù)調(diào)度實(shí)現(xiàn)方法
在沒(méi)有使用spring boot之前,我們的做法是在配置文件中定義一個(gè)任務(wù)池,然后將@Async注解的任務(wù)丟到任務(wù)池中去執(zhí)行,那么在spring boot中,怎么來(lái)實(shí)現(xiàn)異步任務(wù)的調(diào)用了,下面通過(guò)本文給大家講解,需要的朋友參考下2018-02-02

