这篇文章给大家介绍异步请求如何利用Spring Boot来实现,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
首先说一下几个要点:
@WebFilter 和 @WebServlet 注解中的 asyncSupported = true 属性
异步处理的servlet若存在过滤器,则过滤器的注解@WebFilter应设置asyncSupported=true,
否则会报错 A filter or servlet of the current chain does not support asynchronous operations.
2、@EnableAsync 注解
Spring Boot 默认添加了一些拦截 @WebServlet(urlPatterns = "/xs/cometservlet", asyncSupported = true)//异步处理的servlet若存在过滤器,则过滤器的注解@WebFilter应设置asyncSupported=true,//否则会报错A filter or servlet of the current chain does not support asynchronous operations.public class CometServlet extends HttpServlet { private static final long serialVersionUID = -8685285401859800066L; private final Queue<AsyncContext> asyncContexts = new LinkedBlockingQueue<>(); private final Thread generator = new Thread("Async Event generator") { @Override public void run() { while (!generator.isInterrupted()) {// 线程有效 try { while (!asyncContexts.isEmpty()) {// 不为空 TimeUnit.SECONDS.sleep(10);// 秒,模拟耗时操作 AsyncContext asyncContext = asyncContexts.poll(); HttpServletResponse res = (HttpServletResponse) asyncContext.getResponse(); res.getWriter().write("{\"result\":\"OK - "+System.currentTimeMillis()+"\"}"); res.setStatus(HttpServletResponse.SC_OK); res.setContentType("application/json"); asyncContext.complete();// 完成 } } catch (InterruptedException e) { Thread.currentThread().interrupt(); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } }; @Override public void init() throws ServletException { super.init(); generator.start(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println(">>>>>>>>>>CometServlet Request<<<<<<<<<<<"); doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { AsyncContext asyncContext = req.startAsync(); asyncContext.setTimeout(20 * 1000L); asyncContexts.offer(asyncContext); } @Override public void destroy() { super.destroy(); generator.interrupt(); }}