1.Configuration(注册asyncRestTemplate bean)
@Bean
public AsyncRestTemplate asyncRestTemplate(){
return new AsyncRestTemplate();
}
2.Controller
@Autowired
private AsyncRestTemplate asyncRestTemplate;
@RequestMapping(value = "/deferred",produces = "text/plain; charset=UTF-8")
@ResponseBody
public DeferredResult deferredResultExam(String url) {
final DeferredResult result = new DeferredResult(2000l, "timeoutPage");
ListenableFuture> future = asyncRestTemplate.getForEntity(url, String.class);
future.addCallback(
new ListenableFutureCallback>() {
@Override
public void onSuccess(ResponseEntity response) {
System.out.println("Success");
result.setResult(response.getBody());
}
@Override
public void onFailure(Throwable t) {
System.out.println("Failure");
result.setErrorResult(t.getMessage());
}
});
return result;
}
二.以下代码来源于:https://github.com/spring-projects/spring-mvc-showcase/blob/master/src/main/java/org/springframework/samples/mvc/async/CallableController.java
@RequestMapping("/view")
public Callable callableWithView(final Model model) {
return new Callable() {
@Override
public String call() throws Exception {
Thread.sleep(2000);
model.addAttribute("foo", "bar");
model.addAttribute("fruit", "apple");
return "views/html";
}
};
}
2.使用@ResponseBody的例子:
@RequestMapping("/response-body")
public @ResponseBody Callable callable() {
return new Callable() {
@Override
public String call() throws Exception {
Thread.sleep(2000);
return "Callable result";
}
};
}
3.处理可能发生异常的例子(异常的处理是放在Controller的另一个方法,例如像下面,详细参考Making a Controller Method Asynchronous的Exceptions)
@RequestMapping("/exception")
public @ResponseBody Callable callableWithException(
final @RequestParam(required=false, defaultValue="true") boolean handled) {
return new Callable() {
@Override
public String call() throws Exception {
Thread.sleep(2000);
if (handled) {
// see handleException method further below
throw new IllegalStateException("Callable error");
}
else {
throw new IllegalArgumentException("Callable error");
}
}
};
}
@ExceptionHandler
@ResponseBody
public String handleException(IllegalStateException ex) {
return "Handled exception: " + ex.getMessage();
}
4.处理可自定义超时的例子,比如此例将异步处理的超时时间设为1s(tomcat的默认值是10s)
@RequestMapping("/custom-timeout-handling")
public @ResponseBody WebAsyncTask callableWithCustomTimeoutHandling() {
Callable callable = new Callable() {
@Override
public String call() throws Exception {
Thread.sleep(2000);
return "Callable result";
}
};
return new WebAsyncTask(1000, callable);
}
超时可使用WebAsyncTask.onTimeout回调来处理.