SpringMVC异步请求

编程

AsyncController

@Controller

public class AsyncController {

/**

* 1. 控制器返回Callable

* 2. Spring异步处理,将Callable提交到TaskExecutor,使用隔离的线城进行执行

* 3. DispatcherServlet和所有的Filter退出线程,但是response保持打开状态

* 4. Callable返回结果,SpringMVC将请求重新派发给容器,恢复之前的处理

* 5. 根据Callable返回的结果,SpringMVC继续进行视图渲染等流程(从请求开始到试图渲染)

*

* 目标方法执行之前.........

* 主线程开始......Thread[http-nio-80-exec-1,5,main]>>>1591364759808

* 主线程结束......Thread[http-nio-80-exec-1,5,main]>>>1591364759815

*

* =================DispatcherServlet和所有的Filter退出线程==========

*

* =================等待Callable执行完成==========

*

* 副线程开始......Thread[MvcAsync1,5,main]>>>1591364759837

* 副线程结束......Thread[MvcAsync1,5,main]>>>1591364761838

*

* =================Callable执行完成==========

*

* 目标方法执行之前.........

* 目标方法执行之后.........

* 页面加载完成之后.........

*

* 异步的拦截器:

* 1. 原生API的AsyncListener

* 2. SpringMVC,实现AsyncHandlerInterceptor

*/

@ResponseBody

@RequestMapping("/async01")

public Callable<String> async01() {

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(2000);

System.out.println("副线程结束......" + Thread.currentThread() + ">>>" + System.currentTimeMillis());

return "Callable<String> async01()";

}

};

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

return callable;

}

@ResponseBody

@RequestMapping("/createOrder")

public DeferredResult<Object> createOrder() {

DeferredResult<Object> deferredResult = new DeferredResult<Object>(3000L, "createOrder fail");

DeferredResultQueue.save(deferredResult);

return deferredResult;

}

@ResponseBody

@RequestMapping("/create")

public String create() {

String orderId = UUID.randomUUID().toString();

DeferredResult deferredResult = DeferredResultQueue.get();

deferredResult.setResult(orderId);

return "success========" + orderId;

}

}

DeferredResultQueue.class

public class DeferredResultQueue {

public static Queue<DeferredResult<Object>> queue = new ConcurrentLinkedQueue<DeferredResult<Object>>();

public static void save(DeferredResult<Object> deferredResult) {

queue.add(deferredResult);

}

public static DeferredResult<Object> get() {

return queue.poll();

}

}

以上是 SpringMVC异步请求 的全部内容, 来源链接: utcz.com/z/517158.html

回到顶部