根據Spring的文檔說明,默認採用的是單線程的模式的。因此在Java應用中,絕大多數狀況下都是經過同步的方式來實現交互處理的。html
那麼當多個任務的執行勢必會相互影響。例如,若是A任務執行時間比較長,那麼B任務必須等到A任務執行完畢後纔會啓動執行。又如在處理與第三方系統交互的時候,容易形成響應遲緩的狀況,以前大部分都是使用多線程來完成此類任務,其實,在spring3.x
以後,已經內置了@Async來完美解決這個問題。java
在解釋以前,咱們先來看兩者的定義:spring
就是整個處理過程順序執行,當各個過程都執行完畢,並返回結果。數據庫
則是隻是發送了調用的指令,調用者無需等待被調用的方法徹底執行完畢;而是繼續執行下面的流程。springboot
例如, 在某個調用中,須要順序調用A,B,C三個過程方法:
如他們都是同步調用,則須要將他們都順序執行完畢以後,方算做過程執行完畢;如B爲一個異步的調用方法,則在執行完A以後,調用B,並不等待B完成,而是執行開始調用C,待C執行完畢以後,就意味着這個過程執行完畢了。多線程
如圖所示:
app
在Java中,通常在處理相似的場景之時,都是基於建立獨立的線程去完成相應的異步調用邏輯,經過主線程和不一樣的線程之間的執行流程,從而在啓動獨立的線程以後,主線程繼續執行而不會產生停滯等待的狀況。或是使用TaskExecutor執行異步線程,參看http://www.cnblogs.com/wihainan/p/6098970.html異步
在Spring中,基於@Async標註的方法,稱之爲異步方法;這些方法在執行的時候,將會在獨立的線程中被執行,調用者無需等待它的完成,便可繼續其餘的操做。async
@Async
註解@Configuration @EnableAsync public class SpringAsyncConfig { ... }
@SpringBootApplication @EnableAsync public class SpringBootApplication { public static void main(String[] args) { SpringApplication.run(SpringBootApplication.class, args); } }
@Async
註解,聲明方法爲異步調用在方法上申明爲異步調用方法便可this
@Async //標註使用 public void downloadFile() throws Exception { ... }
@Async public Future<String> asyncMethodWithReturnType() { System.out.println("Execute method asynchronously - " + Thread.currentThread().getName()); try { Thread.sleep(5000); return new AsyncResult<String>("hello world !!!!"); } catch (InterruptedException e) { // } return null; }
以上示例能夠發現,返回的數據類型爲Future類型,其爲一個接口。具體的結果類型爲AsyncResult,這個是須要注意的地方。
調用返回結果的異步方法示例:
public void testAsyncAnnotationForMethodsWithReturnType() throws InterruptedException, ExecutionException { System.out.println("Invoking an asynchronous method. " + Thread.currentThread().getName()); Future<String> future = asyncAnnotationExample.asyncMethodWithReturnType(); while (true) { ///這裏使用了循環判斷,等待獲取結果信息 if (future.isDone()) { //判斷是否執行完畢 System.out.println("Result from asynchronous process - " + future.get()); break; } System.out.println("Continue doing something else. "); Thread.sleep(1000); } }
這些獲取異步方法的結果信息,是經過不停的檢查Future的狀態來獲取當前的異步方法是否執行完畢來實現的。
在異步方法中,若是出現異常,對於調用者caller而言,是沒法感知的。若是確實須要進行異常處理,則按照以下方法來進行處理:
public class ExceptionHandlingAsyncTaskExecutor implements AsyncTaskExecutor { private AsyncTaskExecutor executor; public ExceptionHandlingAsyncTaskExecutor(AsyncTaskExecutor executor) { this.executor = executor; } ////用獨立的線程來包裝,@Async其本質就是如此 public void execute(Runnable task) { executor.execute(createWrappedRunnable(task)); } public void execute(Runnable task, long startTimeout) { /用獨立的線程來包裝,@Async其本質就是如此 executor.execute(createWrappedRunnable(task), startTimeout); } public Future submit(Runnable task) { return executor.submit(createWrappedRunnable(task)); //用獨立的線程來包裝,@Async其本質就是如此。 } public Future submit(final Callable task) { //用獨立的線程來包裝,@Async其本質就是如此。 return executor.submit(createCallable(task)); } private Callable createCallable(final Callable task) { return new Callable() { public T call() throws Exception { try { return task.call(); } catch (Exception ex) { handle(ex); throw ex; } } }; } private Runnable createWrappedRunnable(final Runnable task) { return new Runnable() { public void run() { try { task.run(); } catch (Exception ex) { handle(ex); } } }; } private void handle(Exception ex) { //具體的異常邏輯處理的地方 System.err.println("Error during @Async execution: " + ex); } }
分析: 能夠發現其是實現了AsyncTaskExecutor, 用獨立的線程來執行具體的每一個方法操做。在createCallable和createWrapperRunnable中,定義了異常的處理方式和機制。
handle()
就是將來咱們須要關注的異常處理的地方。
xml配置文件中的內容:
<task:annotation-driven executor="exceptionHandlingTaskExecutor" scheduler="defaultTaskScheduler" /> <bean id="exceptionHandlingTaskExecutor" class="nl.jborsje.blog.examples.ExceptionHandlingAsyncTaskExecutor"> <constructor-arg ref="defaultTaskExecutor" /> </bean> <task:executor id="defaultTaskExecutor" pool-size="5" /> <task:scheduler id="defaultTaskScheduler" pool-size="1" />
也可使用註解的形式將其配置註冊到bean中。
在@Async
標註的方法,同時也使用@Transactional
進行標註;在其調用數據庫操做之時,將沒法產生事務管理的控制,緣由就在於其是基於異步處理的操做。
那該如何給這些操做添加事務管理呢?
能夠將須要事務管理操做的方法放置到異步方法內部,在內部被調用的方法上添加@Transactional
方法A, 使用了@Async
/@Transactional
來標註,可是沒法產生事務控制的目的。
方法B, 使用了@Async
來標註,B中調用了C、D,C/D分別使用@Transactional
作了標註,則可實現事務控制的目的。
[1]、http://www.javashuo.com/article/p-hxokluvs-gn.html
[2]、http://www.cnblogs.com/wihainan/p/6098970.html