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


分享到:


相關文章: