解决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);//设置子线程共享
发布了40 篇原创文章 · 获赞 15 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/lvxiucai/article/details/101758179