servlet3.0异步请求的好处
提高吞吐, 减少tomcat线程数量
代码相关
1.返回 Callable 来完成异步处理
@RequestMapping(method=RequestMethod.POST)
public Callable<String> processUpload(final MultipartFile file) {
return new Callable<String>() {
public Object call() throws Exception {
// ...
return "someView";
}
};
}
2.返回 DeferredResult
@RequestMapping("/quotes")
@ResponseBody
public DeferredResult quotes() {
DeferredResult deferredResult = new DeferredResult();
// Add deferredResult to a Queue or a Map...
return deferredResult;
}
// In some other thread..
// Set the return value on the deferredResult
deferredResult.set(data);
区别:
1.Callable:springMVC开启一个Callable新线程,利用TaskExecutor管理新产生的线程
2.第二种:自己管理线程池.
配置相关
1.tomcat7.0及以上;
2.spring 3.2及以上;
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"
default-autowire="byName">
<mvc:annotation-driven>
<mvc:async-support default-timeout="3000"/>
</mvc:annotation-driven>
3.web.xml 配置async-supported
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<filter>
<async-supported>true</async-supported>
</filter>
<servlet>
<async-supported>true</async-supported>
</servlet>