子线程无法获取主线程的request

傻男人 1年前 ⋅ 687 阅读

子线程无法获取主线程的request

错误的日志

java.lang.IllegalStateException: 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 expose the current request.
一般的方式(此种方式线程池获取还是为空):
RequestContextHolder.setRequestAttributes(RequestContextHolder.getRequestAttributes(), true);
线程池的方式:
添加TaskDecorator的实现类
public class ContextDecorator implements TaskDecorator {
    @Override
    public Runnable decorate(Runnable runnable) {
        try{
            RequestAttributes request = RequestContextHolder.currentRequestAttributes();
            RequestContextHolder.setRequestAttributes(request,true);
            return ()-> runnable.run();
        }catch (Exception e){
            log.info("----------------获取request出错---------");
            return ()-> RequestContextHolder.resetRequestAttributes();
        }
    }
}
将TaskDecorator的实现类添加到线程池的属性中
executor.setTaskDecorator(new ContextDecorator());

全部评论: 0

    我有话说: