Spring MVC 异步请求 Callable

对于有的请求业务处理流程可能比较耗时,比如长查询,远程调用等,主线程会被一直占用,而tomcat线程池线程有限,处理量就会下降

servlet3.0以后提供了对异步处理的支持,springmvc封装了异步处理,满足用户请求后,主线程很快结束,并开启其它线程处理任务,并将处理结果响应用户,而主线程就可以接收更多请求。

@Controller
public class AsycController {
    @RequestMapping("asyc")
    @ResponseBody
    public Callable<String> asyc(){
        System.out.println("主线程开始..."+Thread.currentThread()+"....."+System.currentTimeMillis());

        Callable<String> callable=new Callable<String>() {
            public String call() throws Exception {
                System.out.println("异步线程开始..."+Thread.currentThread()+"....."+System.currentTimeMillis());
                Thread.sleep(5000);
                System.out.println("异步线程结束..."+Thread.currentThread()+"....."+System.currentTimeMillis());
                return "asyc ";
            }
        };


        System.out.println("主线程结束..."+Thread.currentThread()+"....."+System.currentTimeMillis());
        return callable;
    }
}

   

1,springmvc开启副线程处理业务(将Callable 提交到 TaskExecutor)

2,DispatcherServlet和所有的Filter退出web容器的线程,但是response 保持打开状态

3,Callable返回结果,SpringMVC将请求front/test重新派发给容器(再重新请求一次asyc),恢复之前的处理;

4,DispatcherServlet重新被调用,将结果返回给用户

猜你喜欢

转载自www.cnblogs.com/qin1993/p/11935027.html