亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb

首頁 > 開發 > Java > 正文

Spring中@Async注解執行異步任務的方法

2024-07-14 08:41:10
字體:
來源:轉載
供稿:網友

引言

在業務處理中,有些業務使用異步的方式更為合理。比如在某個業務邏輯中,把一些數據存入到redis緩存中,緩存只是一個輔助的功能,成功或者失敗對主業務并不會產生根本影響,這個過程可以通過異步的方法去進行。

Spring中通過在方法上設置@Async注解,可使得方法被異步調用。也就是說該方法會在調用時立即返回,而這個方法的實際執行交給Spring的TaskExecutor去完成。

代碼示例

項目是一個普通的Spring的項目,Spring的配置文件:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:context="http://www.springframework.org/schema/context"  xmlns:task="http://www.springframework.org/schema/task"  xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context.xsd  http://www.springframework.org/schema/task  http://www.springframework.org/schema/task/spring-task.xsd"> <!-- 包掃描 --> <context:component-scan base-package="com.lzumetal.ssm"/> <!-- 執行異步任務的線程池TaskExecutor --> <task:executor id="myexecutor" pool-size="5" /> <task:annotation-driven executor="myexecutor"/></beans>

兩個Service類:

package com.lzumetal.ssm.anotation.service;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.concurrent.ExecutionException;import java.util.concurrent.Future;/** * 業務Service */@Servicepublic class BusinessService { private static final Logger log = LoggerFactory.getLogger(BusinessService.class); @Autowired private CacheService cacheService; public void doBusiness() {  log.error("start to deal with our business");  cacheService.cacheData();  log.error("comlete service operation"); } /**  * 獲取異步方法執行的返回值  */ public void doBusinessWithAsyncReturn() throws ExecutionException, InterruptedException {  log.error("start to deal with our business");  Future<String> future = cacheService.cacheDataWithReturn();  log.error(future.get()); //future.get()方法是會阻塞的  log.error("comlete service operation"); }}
package com.lzumetal.ssm.anotation.service;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.scheduling.annotation.Async;import org.springframework.scheduling.annotation.AsyncResult;import org.springframework.stereotype.Service;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;/** * 緩存服務 */@Servicepublic class CacheService { private static final Logger log = LoggerFactory.getLogger(CacheService.class); @Async(value = "myexecutor") //指定執行任務的TaskExecutor public void cacheData() {  try {   TimeUnit.SECONDS.sleep(3L);  } catch (InterruptedException e) {   e.printStackTrace();  }  log.error("success store the result to cache"); } @Async public Future<String> cacheDataWithReturn() {  try {   TimeUnit.SECONDS.sleep(3L);  } catch (InterruptedException e) {   e.printStackTrace();  }  log.error("success store the result to cache");  //返回的結果需要通過AsyncResult這個類包裝  return new AsyncResult<>("Async operation success"); }}

測試類:

package com.lzumetal.ssm.anotation.test;import com.lzumetal.ssm.anotation.service.BusinessService;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.util.concurrent.TimeUnit;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = {"classpath:spring-context.xml"})public class MainTest { @Autowired private BusinessService businessService; @Test public void test() throws InterruptedException {  businessService.doBusiness();  //不讓主線程過早結束,否則控制臺看不到異步方法中的輸出內容  TimeUnit.SECONDS.sleep(5L);   } @Test public void testAsyncReturn() throws Exception {  businessService.doBusinessWithAsyncReturn();  TimeUnit.SECONDS.sleep(5L); }}

執行test()方法的結果:

22:20:33,207  INFO main support.DefaultTestContextBootstrapper:260 - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
22:20:33,226  INFO main support.DefaultTestContextBootstrapper:209 - Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
22:20:33,227  INFO main support.DefaultTestContextBootstrapper:187 - Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@100fc185, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@643b1d11, org.springframework.test.context.support.DirtiesContextTestExecutionListener@2ef5e5e3, org.springframework.test.context.transaction.TransactionalTestExecutionListener@36d4b5c, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@6d00a15d]22:20:33,324  INFO main xml.XmlBeanDefinitionReader:317 - Loading XML bean definitions from class path resource [spring-context.xml]
22:20:33,585  INFO main support.GenericApplicationContext:583 - Refreshing org.springframework.context.support.GenericApplicationContext@4f7d0008: startup date [Wed May 30 22:20:33 CST 2018]; root of context hierarchy
22:20:33,763  INFO main concurrent.ThreadPoolTaskExecutor:165 - Initializing ExecutorService 
22:20:33,766  INFO main support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker:325 - Bean 'myexecutor' of type [org.springframework.scheduling.config.TaskExecutorFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
22:20:33,767  INFO main support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker:325 - Bean 'myexecutor' of type [org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
22:20:34,107 ERROR main service.BusinessService:24 - start to deal with our business
22:20:34,113 ERROR main service.BusinessService:26 - comlete service operation
22:20:37,166 ERROR myexecutor-1 service.CacheService:28 - success store the result to cache
22:20:39,117  INFO Thread-0 support.GenericApplicationContext:984 - Closing org.springframework.context.support.GenericApplicationContext@4f7d0008: startup date [Wed May 30 22:20:33 CST 2018]; root of context hierarchy
22:20:39,118  INFO Thread-0 concurrent.ThreadPoolTaskExecutor:203 - Shutting down ExecutorService

執行testAsyncReturn()方法的結果:

21:38:16,908  INFO main support.DefaultTestContextBootstrapper:260 - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
21:38:16,926  INFO main support.DefaultTestContextBootstrapper:209 - Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
21:38:16,927  INFO main support.DefaultTestContextBootstrapper:187 - Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@100fc185, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@643b1d11, org.springframework.test.context.support.DirtiesContextTestExecutionListener@2ef5e5e3, org.springframework.test.context.transaction.TransactionalTestExecutionListener@36d4b5c, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@6d00a15d]21:38:17,025  INFO main xml.XmlBeanDefinitionReader:317 - Loading XML bean definitions from class path resource [spring-context.xml]
21:38:17,263  INFO main support.GenericApplicationContext:583 - Refreshing org.springframework.context.support.GenericApplicationContext@4f7d0008: startup date [Wed May 30 21:38:17 CST 2018]; root of context hierarchy
21:38:17,405  INFO main concurrent.ThreadPoolTaskExecutor:165 - Initializing ExecutorService 
21:38:17,407  INFO main support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker:325 - Bean 'myexecutor' of type [org.springframework.scheduling.config.TaskExecutorFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
21:38:17,407  INFO main support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker:325 - Bean 'myexecutor' of type [org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
21:38:17,692 ERROR main service.BusinessService:35 - start to deal with our business
21:38:20,833 ERROR myexecutor-1 service.CacheService:39 - success store the result to cache
21:38:20,834 ERROR main service.BusinessService:37 - Async operation success
21:38:20,835 ERROR main service.BusinessService:38 - comlete service operation
21:38:25,838  INFO Thread-0 support.GenericApplicationContext:984 - Closing org.springframework.context.support.GenericApplicationContext@4f7d0008: startup date [Wed May 30 21:38:17 CST 2018]; root of context hierarchy
21:38:25,839  INFO Thread-0 concurrent.ThreadPoolTaskExecutor:203 - Shutting down ExecutorService

@Async的使用注意點

  1. 返回值:不要返回值直接void;需要返回值用AsyncResult或者CompletableFuture
  2. 可自定義執行器并指定例如:@Async("otherExecutor")
  3. @Async必須不同類間調用: A類—>B類.C方法()(@Async注釋在B類/方法中),如果在同一個類中調用,會變同步執行,例如:A類.B()—>A類.@Async C()。
  4. @Async也可以加到類,表示這個類的所有方法都是異步執行,并且方法上的注解會覆蓋類上的注解。但一般不這么用!

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到JAVA教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb
日本午夜在线亚洲.国产| 欧美国产激情18| 日本19禁啪啪免费观看www| 欧美国产日韩一区二区三区| 欧美日韩国产在线看| 91豆花精品一区| 成人黄色影片在线| 97国产精品视频| 精品国产一区二区三区四区在线观看| 亚洲一区二区黄| 国产午夜精品一区二区三区| 亚洲国产精品视频在线观看| 国产精品福利无圣光在线一区| 国产精品678| 久久久久久国产精品三级玉女聊斋| 国产精品丝袜久久久久久高清| 亚洲一区中文字幕在线观看| 国产精品自拍偷拍| 精品视频久久久久久久| 国产精品永久免费| 91精品视频大全| 国产视频精品xxxx| 久久99精品久久久久久噜噜| 欧美一级大片在线免费观看| 情事1991在线| 一区二区欧美久久| 日韩av综合中文字幕| 成人精品视频在线| 久久亚洲精品一区| 国产欧美精品日韩| 久久亚洲精品一区二区| 日韩av手机在线观看| 亚洲欧美在线一区| 久久九九有精品国产23| 亚洲深夜福利视频| 国产精品h在线观看| 韩国19禁主播vip福利视频| 热久久免费视频精品| 久久99精品久久久久久琪琪| 成人在线国产精品| 国产一区二区三区视频在线观看| 8050国产精品久久久久久| www.亚洲天堂| 少妇高潮久久久久久潘金莲| 91精品国产综合久久香蕉最新版| 日日骚久久av| 国产精品福利观看| 国内精品一区二区三区四区| 成人精品久久久| 92版电视剧仙鹤神针在线观看| 国产精品视频一区二区高潮| 国产精品免费视频xxxx| 成人自拍性视频| 亚洲精品国产免费| 浅井舞香一区二区| 久久久久99精品久久久久| 在线播放国产精品| 久久国产精品视频| 国产精品日韩欧美| 92国产精品久久久久首页| 欧美成人免费一级人片100| 亚洲精品国产美女| 国产欧美日韩最新| 91亚洲精品久久久| 亚洲综合大片69999| 91社区国产高清| 91精品久久久久久久久久| 国产婷婷成人久久av免费高清| 欧美在线视频观看免费网站| 97视频国产在线| 久久影视免费观看| 亚洲伊人一本大道中文字幕| 亚洲美女自拍视频| 欧美一级视频免费在线观看| 色妞色视频一区二区三区四区| 亚洲精品网址在线观看| 精品国产乱码久久久久久虫虫漫画| 日本老师69xxx| 欧美精品videos性欧美| 97视频免费看| 国产精品一区二区女厕厕| 欧美激情小视频| 亚洲一区二区久久| 久久精品国产69国产精品亚洲| 中文字幕精品www乱入免费视频| 日日狠狠久久偷偷四色综合免费| 91免费在线视频网站| 欧美精品精品精品精品免费| 欧美亚洲另类制服自拍| 亚洲精品av在线| 国产精品久久久久久久久免费看| 久久精品夜夜夜夜夜久久| 尤物99国产成人精品视频| 欧美在线视频在线播放完整版免费观看| 中文精品99久久国产香蕉| 精品日韩视频在线观看| 久久久亚洲国产天美传媒修理工| 少妇久久久久久| 成人免费在线视频网站| 原创国产精品91| 亚洲第一二三四五区| 亚洲综合av影视| 欧美极品欧美精品欧美视频| 国产精品亚洲第一区| 欧美精品一区二区三区国产精品| 尤物九九久久国产精品的特点| 欧美一区二区三区免费观看| 国产一区二区免费| 97视频在线观看成人| 成人免费自拍视频| 97国产一区二区精品久久呦| 国产亚洲激情在线| 国产精品第三页| 欧美精品aaa| 国产精品入口日韩视频大尺度| 国产精品美女久久久久久免费| 国产免费一区二区三区在线能观看| 久久精品国产欧美激情| 国产原创欧美精品| 色青青草原桃花久久综合| 亚洲影院在线看| 欧洲精品毛片网站| 91精品视频免费观看| 91久久综合亚洲鲁鲁五月天| 欧美一区二区影院| 亚洲欧美日韩中文在线| 欧美激情精品久久久久久久变态| 国产精品福利观看| 欧美黑人又粗大| 欧美精品在线免费观看| 亚洲成人免费在线视频| 欧美午夜精品久久久久久浪潮| 欧美成人精品在线视频| 国产精品一区二区三区毛片淫片| 国产精品∨欧美精品v日韩精品| 国产精品夫妻激情| 欧美日韩成人精品| 国产精品久久久久久久久久久不卡| 精品久久久久国产| 国内精品久久久久久影视8| 亚洲国产精品女人久久久| 日韩中文字幕在线精品| 国产精品久久久久久超碰| 欧美成人免费在线视频| 97国产在线视频| 国产精品自拍小视频| 国内外成人免费激情在线视频| 激情成人在线视频| 一区二区三区黄色| 色播久久人人爽人人爽人人片视av| 亚洲色图15p| 成人在线视频网站| 日本免费在线精品| 国产在线视频不卡| 亚洲丝袜一区在线| 91精品在线看| 亚洲欧美制服第一页| 日韩av在线不卡| 国产免费一区二区三区在线能观看| 日韩高清免费在线| 久久国产精彩视频| 欧美视频免费在线观看| 久久亚洲影音av资源网| 最新日韩中文字幕|