基于Servlet3.0的异步处理,springmvc的异步处理
控制器返回callable, spring mvc异步处理,将callable提交到TaskExecutor 使用一个隔离线程进行执行
DispatcherServlet和所有的Filter退出web容器的线程,但是response保持打开状态
Callable返回结果, Spring mvc 将请求重新派发给容器,回复之前的处理
根据Callable返回的结果,Springmvc继续进行视图渲染流程等(从收请求一直到视图渲染)
两次 preHandler哦
异步拦截器:
1 原生API的AsyncListener
2 Spring mvc 实现AsyncHandlerInterceptor
消息中间件的方式:
Spring mvc也有这样的类似的机制
Controller:
@Controller public class SpringMVCAsyncController { @ResponseBody @RequestMapping("/createOrder") public DeferredResult<Object> createOrder(){ //3秒没有响应 就报错 DeferredResult<Object> deferredResult = new DeferredResult<Object>((long)3000, "error: create fail..."); DeferredResultQueue.save(deferredResult); return deferredResult; } @ResponseBody @RequestMapping("/create") public String create() { //创建订单 String orderNum = UUID.randomUUID().toString(); //拿出上面保存的DeferredResultQueue DeferredResult<Object> deferredResult = DeferredResultQueue.get(); deferredResult.setResult(orderNum); //设置订单号createOrder() 就会得到立即返回 return "success===>orderNum:"+orderNum; } }
队列:
public class DeferredResultQueue { private 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(); } }
请求: 3秒没有赋值 就报错哈