参考文章: https://www.cnblogs.com/guogangj/p/5457959.html https://www.jianshu.com/p/ecc6f5168aef https://www.iteye.com/blog/elim-2426566 https://www.cnblogs.com/yangzhilong/p/3725128.html
Servlet 3.0或以上的版本开始支持异步。 Spring MVC 3.2 开始支持异步。
(1)POM.xml里 javax.servlet-api用3.1.0或更高版本
(2)web.xml里 web-app的声明用3.0版本
所有filter和org.springframework.web.servlet.DispatcherServlet,都增加 <async-supported>true</async-supported>
如:
<filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <async-supported>true</async-supported> </filter>
<servlet> <servlet-name>SpringMVCServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> WEB-INF/spring/appServlet/servlet-context.xml </param-value> </init-param> <load-on-startup>0</load-on-startup> <async-supported>true</async-supported> </servlet>
(3)springMvc的配置文件xml里, 声明用3.2版本或以上。
增加 <mvc:annotation-driven> <mvc:async-support default-timeout="15000"/> </mvc:annotation-driven> 有个异步超时时间的设置。
(4)修改Controller
@RequestMapping(value = "/query") @ResponseBody public DeferredResult<String> query(HttpServletRequest request,HttpServletResponse resp) { final DeferredResult<String> deferredResult = new DeferredResult<String>();
// 超时设置 deferredResult.onTimeout(new Runnable() {
@Override public void run() { deferredResult.setResult("---超时啦---");
} }); //异步执行你的业务,在里面调用deferredResult.setResult()设置结果即可。 //先返回 return deferredResult; }
|