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

前端 0

问题现象

        今天发现线上的一个报警,定时任务执行的时候发生了如下报警,哎就奇怪了为啥会有这种的报警呢,测试和预发环境都没有问题呀。通过一通排查,最终发现是代码使用的地方有问题,估做一个记录,避免以后再踩坑。

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: In this case, use RequestContextListener or RequestContextFilter to e xpose the current request.  

问题原因

        首先翻译上面的报错如下:

        没有找到与线程绑定的请求:你是指在实际的web请求之外引用请求属性,还是在最初接收请求的线程之外处理请求?如果你确实在web请求中操作,但仍然收到这个消息,那么你的代码可能在DispatcherServlet之外运行:在这种情况下,使用RequestContextListener或RequestContextFilter来暴露当前请求。

        因为这个错误信息是与Spring框架相关的,通常发生在尝试在实际的web请求之外访问请求属性,或者在最初接收请求的线程之外处理请求时。如果你正在处理一个web请求但仍然收到这个错误信息,那么很可能是因为你的代码在DispatcherServlet之外运行。DispatcherServlet负责处理web请求并在Spring框架中管理请求的生命周期。

问题解决:

        看到这其实代码也就显而易见了,代码里有一段这个逻辑,通过请求上下文获取用户信息。这也就是定时任务发起的请求为啥会报这个错误了。解决就是不能通过Web请求获取用户信息终于搞明白了。

((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest()

 

也许您对下面的内容还感兴趣: