Spring MVC的異步請求WebAsyncTask

在業務處理中,如果我們需要超時處理的回調或者錯誤處理的回調,我們可以使用WebAsyncTask代替Callable實際使用中。在實際開發中我並不建議直接使用Callable ,而是使用Spring提供的WebAsyncTask 代替,它包裝了Callable,功能更強大些,支持超時回調,完成回調等附和功能。

<code>@RequestMapping("async/webAsyncTask")
@ResponseBody
public WebAsyncTask<string>asyncTask(){
System.out.println("main thread:"+Thread.currentThread().getName());
System.out.println("begin execute task"+System.currentTimeMillis());
Callable<string> callable = new Callable<string>() {
@Override
public String call() throws Exception {
System.out.println("exec thread:"+Thread.currentThread().getName());
Thread.sleep(2000);
return "sucess";
}
};

//使用webAsyncTask包裝callable,支持多種構造方式,設置超時時間3秒
WebAsyncTask<string> webAsyncTask = new WebAsyncTask<string>(3000,callable);

//注意onCompletion表示任務完成回調,無論超時,錯誤都會執行,類似於finnally
webAsyncTask.onCompletion(new Runnable() {
@Override
public void run() {
System.out.println("異步執行完成回調任務");
}
});

//異步任務執行超時觸發
webAsyncTask.onTimeout(new Callable<string>() {
@Override
public String call() throws Exception {
System.out.println("異步執行任務超時");
return "execute task time out";
}
});
System.out.println("end execute task"+System.currentTimeMillis());
return webAsyncTask;
}/<string>/<string>/<string>/<string>/<string>/<string>/<code>

1.代碼中設置了超時時間為3s,若業務處理時間超過3s,所以會執行onTimeout這個回調函數。執行結果返回“execute task time out。

2.onCompletion在任務完成時執行回調,無論執行任務發生超時,異常會觸發執行,類似於finnally作用。

Spring MVC的異步請求WebAsyncTask


分享到:


相關文章: