解决No thread-bound request found: Are you referring to request attributes outside of an actual web re

使用背景:今天在spring-cloud项目中,使用多线程异步调用微服务出现的错误 

No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request。

具体场景

我的微服务调用有自己的统一拦截器RequestIntercepter来输出调用信息,在其中使用RequestContextHolder来获取request信息,发现异步调用时,主线程结束后,子线程就获取不到request,会报以上错误信息。

解决思路:

1.将主线程的request和session信息放进ThreadLocal里,透传到子线程再去获取,这种我还没试(稍后有时间弄)。

2.在开启新线程之前,将servletRequestAttributes设置为子线程共享

ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();

RequestContextHolder.setRequestAttributes(servletRequestAttributes,true);//设置子线程共享

阿里云服务器低至1折14元/月--建站首选

背景2:如果非web请求(定时任务或者消息消费)造成的,可以通过以下方式设置,在触发报错的类里面加上一个自己封装的方法getRequestAttributesSafely(),具体可以参考下面:

    public RequestAttributes getRequestAttributesSafely(){
        RequestAttributes requestAttributes = null;
        try{
            requestAttributes = RequestContextHolder.currentRequestAttributes();
        }catch (IllegalStateException e){
            requestAttributes = new NonWebRequestAttributes();
        }
        return requestAttributes;
    }

  • 26
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 23
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 23
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值