- ServletRequestAttributes对象获取不到的情况一般分为以下几种情况:
1、异步线程调用。例如@Async注解的情况
2、子线程调用的情况。由于RequestContextHolder使用ThreadLocal共享数据,子线程会导致丢掉ThreadLocal中原来线程的数据。
3、非Web上下文的情况下调用。例如rpc框架这种。
查看了下代码,发现是使用了CompletableFuture的子线程方式,导致在RequestContextHolder中获取不到对象。
- 解决方法比较简单:
1、参数透传 修改接口,把需要在ThreadLocal中获取的参数透传到其它方法中。
2、重置上下文对象 在子线程中重置RequestContextHolder对象。
// 从主线程获取用户数据 放到局部变量中
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
CompletableFuture<Void> testFuture = CompletableFuture.runAsync(() -> {
// 把旧RequestAttributes放到新线程的RequestContextHolder中
RequestContextHolder.setRequestAttributes(attributes);
...
}
使用方式1 测试了下,发现问题圆满解决。
原文链接:https://blog.csdn.net/m290345792/article/details/125068018