SpringBoot使用SSE流,打tar包发版后出现问题

SpringBoot使用SSE流,打tar包发版后出现问题

以下纯个人实践,如有问题,还望指正~

出现的问题

出现原因:本地调试SSE推送数据没有问题,但是通过打包为tar包发版之后,出现了以下报错:

主要问题就是:

java.lang.IllegalArgumentException: Async support must be enabled on a servlet and for all filters involved in async request processing. This is done in Java code using the Servlet API or by adding "<async-supported>true</async-supported>" to servlet and filter declarations in web.xml.

贴张图:

企业微信截图_17373652857553

其实这个问题已经说的很明白了,去web.xml文件加上即可,但问题在于这是SpringBoot项目,配置web.xml有点离谱了,于是网络搜索解决方案加上SpringBoot就会获得这些结果:

方案1:给启动类加上注解

@WebFilter(urlPatterns = { "/*" }, asyncSupported = true)

本人项目实测没用,但有人成功过,列在这里

方案2:加过滤器

@Component
public class AsyncSupportFilter extends OncePerRequestFilter {
   @Override
   protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
       request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, true);
       chain.doFilter(request, response);
  }
}

这个里面就能看出来,还是在尝试启用asyncSupported,但我这边实测还是不行

那么提供最终的解决办法,个人亲测可用,不排除个例问题 ,仅供参考

实现方案:

/**
* 异步请求支持过滤器配置类
* 用于启用 Servlet 异步处理功能
* @author houjinbao
*/
@Configuration
public class AsyncSupportFilter {
   
   /**
    * 注册异步请求过滤器的 Bean
    * @return FilterRegistrationBean 过滤器注册对象
    */
   @Bean
   public FilterRegistrationBean<AsyncRequestFilter> asyncFilterRegistration() {
       // 创建过滤器注册对象
       FilterRegistrationBean<AsyncRequestFilter> registration = new FilterRegistrationBean<>();
       // 设置使用的过滤器
       registration.setFilter(new AsyncRequestFilter());
       // 设置过滤器匹配的 URL 模式,/*表示匹配所有请求
       registration.addUrlPatterns("/*");
       // 启用异步支持
       registration.setAsyncSupported(true);
       // 设置过滤器的优先级为最高
       registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
       return registration;
  }
   
   /**
    * 异步请求过滤器实现类
    * 继承 OncePerRequestFilter 确保每个请求只经过一次过滤器
    */
   private static class AsyncRequestFilter extends OncePerRequestFilter {
       @Override
       protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
               throws ServletException, IOException {
           // 设置请求属性,启用 Tomcat 的异步处理支持
           request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
           // 继续执行过滤器链
           chain.doFilter(request, response);
      }
  }
}

记得启动类加上@EnableAsync

其他方案:

方案4(不保真):

有外国老哥测试,可在TomCat文件里面去修改,配置TomCat的web.xml文件,也可实现

原文:stack overflow 文章

image-20250124142216918

 
posted @   Hlmove  阅读(64)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~
点击右上角即可分享
微信分享提示