spring mvc异步编程入门例子

参考资料:
servlet 3.1规范下载:http://download.oracle.com/otndocs/jcp/servlet-3_1-fr-spec/index.html
spring-framework-reference:17.3.4 Asynchronous Request Processing
Introducing Servlet 3, Async Support:http://spring.io/blog/2012/05/07/spring-mvc-3-2-preview-introducing-servlet-3-async-support/
Techniques for Real-time Updates:http://spring.io/blog/2012/05/08/spring-mvc-3-2-preview-techniques-for-real-time-updates/
Making a Controller Method Asynchronous:http://spring.io/blog/2012/05/10/spring-mvc-3-2-preview-making-a-controller-method-asynchronous/
Adding Long Polling to an Existing Web Application:https://spring.io/blog/2012/05/14/spring-mvc-3-2-preview-adding-long-polling-to-an-existing-web-application
Chat Sample:http://spring.io/blog/2012/05/16/spring-mvc-3-2-preview-chat-sample/


写一个异步方法.
一.

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<String> deferredResultExam(String url) {
	final DeferredResult<String> result = new DeferredResult<String>(2000l, "timeoutPage");
	ListenableFuture<ResponseEntity<String>> future = asyncRestTemplate.getForEntity(url, String.class);
	future.addCallback(
		new ListenableFutureCallback<ResponseEntity<String>>() {
		    @Override
		    public void onSuccess(ResponseEntity<String> 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
1.直接返回视图名的例子:
@RequestMapping("/view")
public Callable<String> callableWithView(final Model model) {
	return new Callable<String>() {
		@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<String> callable() {
	return new Callable<String>() {
		@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<String> callableWithException(
		final @RequestParam(required=false, defaultValue="true") boolean handled) {
	return new Callable<String>() {
		@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<String> callableWithCustomTimeoutHandling() {
	Callable<String> callable = new Callable<String>() {
		@Override
		public String call() throws Exception {
			Thread.sleep(2000);
			return "Callable result";
		}
	};
	return new WebAsyncTask<String>(1000, callable);
}
超时可使用WebAsyncTask.onTimeout回调来处理.
注:如果抛异常Handled exception: Async support must be enabled on a servlet and for all filters involved in async request processing...
请检查Dispatch Servlet和被拦截的filter,都要设置asyncSupport为true,其中AbstractDispatcherServletInitializer里面注册的Dispatch Servlet已设置asyncSupport为true.




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值