温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

异步请求如何利用Spring Boot来实现

发布时间:2020-11-18 15:17:06 来源:亿速云 阅读:251 作者:Leah 栏目:编程语言

这篇文章给大家介绍异步请求如何利用Spring Boot来实现,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

首先说一下几个要点: 

1、@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 默认添加了一些拦截 /* 的过滤器,因为 /* 会拦截所有请求,按理说我们也要设置 asyncSupported=true 属性。因为这些过滤器都是 Spring Boot 初始化的,所以它提供了 @EnableAsync 注解来统一配置,该注解只针对 “非 @WebFilter 和 @WebServlet 注解的有效”,所以我们自己定义的 Filter 还是需要自己配置 asyncSupported=true 的。

3、AsyncContext 对象

获取一个异步请求的上下文对象。

4、asyncContext.setTimeout(20 * 1000L);

我们不能让异步请求无限的等待下去,通过 setTimeout 来设定最大超时时间。

下面通过两种方式来测试异步任务:

先在 SpringBootSampleApplication 上添加 @EnableAsync 注解。

再检查所有自定义的Filter,如存在如下两种情况需要配置 asyncSupported=true

1) 自定义Filter 拦截了 /*

2) 某Filter 拦截了 /shanhy/* ,我们需要执行的异步请求的 Servlet 为 /shanhy/testcomet

方法一:原生Servlet方式

package org.springboot.sample.servlet;

import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * HTTP长连接实现
 *
 * @author 单红宇(365384722)
 * @myblog http://blog.csdn.net/catoop/
 * @create 2016年3月29日
 */
@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();
 }


}

方法二:Controller 方式

@Controller
public class PageController {

 @RequestMapping("/async/test")
 @ResponseBody
 public Callable<String> callable() {
  // 这么做的好处避免web server的连接池被长期占用而引起性能问题,
  // 调用后生成一个非web的服务线程来处理,增加web服务器的吞吐量。
  return new Callable<String>() {
   @Override
   public String call() throws Exception {
    Thread.sleep(3 * 1000L);
    return "小单 - " + System.currentTimeMillis();
   }
  };
 }

}

最后写一个comet.jsp页面测试:

<%@ page pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
 <title>长连接测试</title>
 <script type="text/javascript" src="${pageContext.request.contextPath }/webjarslocator/jquery/jquery.js"></script>
 <script type="text/javascript">
  $(function(){
   function longPolling(){
    $.getJSON('${pageContext.request.contextPath }/xs/cometservlet', function(data){
     console.log(data.result);
     $('#n1').html(data.result);
     longPolling();
    });
   }
   longPolling();

   function longPolling2(){
    $.get('${pageContext.request.contextPath }/async/test', function(data){
     console.log(data);
     $('#n2').html(data);
     longPolling2();
    });
   }
   longPolling2();
  });
 </script>
 </head>

 <body>
 <h2>长连接测试</h2>
 <h3 id="n1"></h3>
 <h3 id="n2"></h3>
 </body>
</html>

关于异步请求如何利用Spring Boot来实现就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI