使用背景:今天在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;
    }

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐