Spring异步Servlet请求

2016-10-26  本文已影响238人  KwTGmu

异步Servlet请求基于Servlet-api 3.0版本以上
所以需要Tomcat7.0以上版本及Jetty8.0以上版本才可以正常运行
软件上需要Spring-Framework v3.2版本以上
spring-config.xml

<mvc:annotation-driven >
    <mvc:async-support default-timeout="15000"></mvc:async-support>
</mvc:annotation-driven>

web.xml

<filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <async-supported>true</async-supported>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>ASYNC</dispatcher>
</filter-mapping>
<servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:/spring/spring-config.xml</param-value>
    </init-param>
    <init-param>
        <param-name>throwExceptionIfNoHandlerFound</param-name>
        <param-value>true</param-value>
    </init-param>
    <async-supported>true</async-supported>
</servlet>
<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

代码可以写为:

@RequestMapping("/time")
public @ResponseBody Callable<String> index() {

    try {
        log.info("异步调用开始啦");
        return new Callable<String>() {
            @Override
            public String call() throws Exception {
                
                log.info("我要冬眠");
                Thread.sleep(5000);
                return "本次处理圆满完成";
            }
        };
    } finally {
        log.info("程序处理结束");
    }
}

其它配置实验中

上一篇下一篇

猜你喜欢

热点阅读