以下代碼創建該註釋。爲方法調用的異步執行創建自定義「Asynch」註釋是個好主意嗎?
/**
* Defining the Asynch interface
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Asynch {}
/**
* Implementation of the Asynch interface. Every method in our controllers
* goes through this interceptor. If the Asynch annotation is present,
* this implementation invokes a new Thread to execute the method. Simple!
*/
public class AsynchInterceptor implements MethodInterceptor {
public Object invoke(final MethodInvocation invocation) throws Throwable {
Method method = invocation.getMethod();
Annotation[] declaredAnnotations = method.getDeclaredAnnotations();
if(declaredAnnotations != null && declaredAnnotations.length > 0) {
for (Annotation annotation : declaredAnnotations) {
if(annotation instanceof Asynch) {
//start the requested task in a new thread and immediately
//return back control to the caller
new Thread(invocation.getMethod().getName()) {
public void execute() {
invocation.proceed();
}
}.start();
return null;
}
}
}
return invocation.proceed();
}
}
而且它使用的方法調用不返回任何內容(無效)。
例,
/**
* So, earlier we had a simple method in our interface which we later
* annotated with the Asynch @interface. Bang! The caller doesn't need
* to worry about it now. This method (no matter who the caller is)
* gets executed asynchronously. Ain't that awesome?
*/
@Asynch
public void refreshSurveyStatusOnResponse(String licenseCode, Integer surveyId);
哪些利弊?如果我們使用消息隊列和工作線程池來解決而不是異步方法調用呢? 從標準的Java而不是這種本土解決方案可以使用什麼解決方案? 上面的方法似乎有一個積壓,Asynch方法調用不會在這種情況下返回任何值上面的代碼將打破。期望異步方法調用的返回值是否合乎邏輯?
謝謝!我有類似的想法,現在他們被驗證! – 2012-03-17 13:31:49