怎么在SpringBoot中利用@Async實(shí)現(xiàn)異步調(diào)用-創(chuàng)新互聯(lián)

本篇文章為大家展示了怎么在Spring Boot中利用@Async實(shí)現(xiàn)異步調(diào)用,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。

創(chuàng)新互聯(lián)專注于開福企業(yè)網(wǎng)站建設(shè),自適應(yīng)網(wǎng)站建設(shè),商城建設(shè)。開福網(wǎng)站建設(shè)公司,為開福等地區(qū)提供建站服務(wù)。全流程按需設(shè)計(jì),專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)

定義一個(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的步驟

第三步:修改單元測試,模擬高并發(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);
  }
 }
 }
}

說明:通過for循環(huán)往上面定義的線程池中提交任務(wù),由于是異步執(zhí)行,在執(zhí)行過程中,利用System.exit(0)來關(guān)閉程序,此時(shí)由于有任務(wù)在執(zhí)行,就可以觀察這些異步任務(wù)的銷毀與Spring容器中其他資源的順序是否安全。

第四步:運(yùn)行上面的單元測試,我們將碰到下面的異常內(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來看,我們很容易的可以想到,在應(yīng)用關(guān)閉的時(shí)候異步任務(wù)還在執(zhí)行,由于Redis連接池先銷毀了,導(dǎo)致異步任務(wù)中要訪問Redis的操作就報(bào)了上面的錯(cuò)。所以,我們得出結(jié)論,上面的實(shí)現(xiàn)方式在應(yīng)用關(guān)閉的時(shí)候是不優(yōu)雅的,那么我們要怎么做呢?

解決方法

要解決上面的問題很簡單,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;
}

說明:setWaitForTasksToCompleteOnShutdown(true)該方法就是這里的關(guān)鍵,用來設(shè)置線程池關(guān)閉的時(shí)候等待所有任務(wù)都完成再繼續(xù)銷毀其他的Bean,這樣這些異步任務(wù)的銷毀就會先于Redis線程池的銷毀。同時(shí),這里還設(shè)置了setAwaitTerminationSeconds(60),該方法用來設(shè)置線程池中任務(wù)的等待時(shí)間,如果超過這個(gè)時(shí)候還沒有銷毀就強(qiáng)制銷毀,以確保應(yīng)用最后能夠被關(guān)閉,而不是阻塞住。

上述內(nèi)容就是怎么在Spring Boot中利用@Async實(shí)現(xiàn)異步調(diào)用,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

新聞標(biāo)題:怎么在SpringBoot中利用@Async實(shí)現(xiàn)異步調(diào)用-創(chuàng)新互聯(lián)
文章出自:http://muchs.cn/article34/dhshpe.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站排名、Google、營銷型網(wǎng)站建設(shè)、服務(wù)器托管、手機(jī)網(wǎng)站建設(shè)、網(wǎng)站改版

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)頁設(shè)計(jì)公司