@Async的簡單用法總結
前言: 在Java應用中,絕大多數情況下都是通過同步的方式來實現交互處理的;但是在處理與第三方系統交互的時
候,容易造成響應遲緩的情況,之前大部分都是使用多線程來完成此類任務,其實,在Spring 3.x之後, 就已經內置了
@ Async來完美解決這個問題,本文將完成介紹@ Async的用法。
1,@Async介紹
在Spring中,基於@ Async標註的方法,稱之為異步方法;這些方法將在執行的時候,將會在獨立的線程中被執行,
調用者無需等待它的完成,即可繼續其他的操作。
如何在Spring中啟用@ Async:
基於Java配置的啟用方式:
@Configuration @EnableAsync public class SpringAsyncConfig { ... }
基於XML配置文件的啟用方式,配置如下:
<task:executor id="myexecutor" pool-size="5" />
<task:annotation-driven executor="myexecutor"/>
以上就是兩種定義的方式。
2, 基於@ Async無返回值調用
@Async //標註使用 public void asyncMethodWithVoidReturnType() { System.out.println("Execute method asynchronously. " + Thread.currentThread().getName()); }
使用的方式非常簡單,一個標註即可解決所有的問題。
3, 基於@ Async返回值的調用
@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的狀態來獲取當前的異步方法是否執行完畢來實現的。
4, 基於@ Async調用中的異常處理機制
在異步方法中,如果出現異常,對於調用者caller而言,是無法感知的。如果確實需要進行異常處理,則按照如下方法來進行處理:
1. 自定義實現AsyncTaskExecutor的任務執行器
在這裏定義處理具體異常的邏輯和方式。
2. 配置由自定義的TaskExecutor替代內置的任務執行器
示例步驟1,自定義的TaskExecutor
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()就是未來我們需要關註的異常處理的地方。配置文件中的內容:
<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" />
分析: 這裏的配置使用自定義的taskExecutor來替代缺省的TaskExecutor。
5, @Async調用中的事務處理機制
在@ Async標註的方法,同時也適用了@ Transactional進行了標註;在其調用數據庫操作之時,將無法產生事務管理
的控制,原因就在於其是基於異步處理的操作。
那該如何給這些操作添加事務管理呢?可以將需要事務管理操作的方法放置到異步方法內部,在內部被調用的方法上
添加@ Transactional.
例如: 方法A,使用了@ Async/@ Transactional來標註,但是無法產生事務控制的目的。
方法B,使用了@ Async來標註, B中調用了C、D,C/D分別使用@ Transactional做了標註,則可實現事務控制的目的。
@Async的簡單用法總結