这篇文章给大家介绍异步请求如何利用Spring Boot来实现,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。首先说一下几个要点: @WEBFilter 和 @WebServlet 注解中的 asyncSupp
这篇文章给大家介绍异步请求如何利用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(); }}
--结束END--
本文标题: 异步请求如何利用Spring Boot来实现
本文链接: https://lsjlt.com/news/226657.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0