异步请求如何利用Spring Boot来实现
这篇文章给大家介绍异步请求如何利用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(); }}
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341