inheritable = true No thread-bound request found: Are you referring
时间: 2023-12-15 12:31:48 浏览: 43
这个错误通常是由于在子线程中访问无法访问到的父线程中的请求属性而引起的。如果您使用的是Spring框架,则可以通过设置`@Async`注释的`mode`属性为`AdviceMode.PROXY`来解决此问题。这将使用代理来确保在子线程中访问父线程中的请求属性。例如:
```java
@Service
public class MyService {
@Async(mode = AdviceMode.PROXY, proxyTargetClass = true)
public void myAsyncMethod() {
// 在这里访问请求属性
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); // ...
}
}
```
相关问题
在 异步方法中 RequestContext日 Ider.setRequestAttributes (RequestContextHolder.getRequestAttributes(), inheritable: true) 这代码失效,是什么原因导致的?该如何处理
这个问题可能由于异步上下文的切换导致的。在异步方法中,可能会发生线程切换,这可能导致请求上下文(RequestContext)丢失。在你提到的代码中,`RequestContextHolder.getRequestAttributes()`返回的是当前线程的请求上下文。
为了解决这个问题,你可以尝试以下几个步骤:
1. 确保你的代码在异步方法执行时,仍然能够获取到正确的请求上下文。有时候,会有一些异步框架或库提供了特定的方法来传递请求上下文,请确保你正确地使用了这些方法。
2. 如果异步方法会导致线程切换,你可以尝试使用`RequestAttributes`的子类`ServletRequestAttributes`来进行上下文传递。这个类可以通过`ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes()`来获取,然后在异步方法中使用`ServletRequestAttributes.setRequestAttributes(requestAttributes, true)`来传递请求上下文。
3. 如果上述步骤都无法解决问题,你可以考虑使用线程池中的线程来执行异步方法。在这种情况下,你需要手动将请求上下文传递给线程池中执行的线程,然后在异步方法中恢复请求上下文。
需要注意的是,以上方法仅适用于基于线程的异步模型。如果你使用的是非阻塞的异步模型,那么你可能需要参考具体框架的文档或寻求相关支持来解决该问题。
/** * Initializes a Thread. * * @param g the Thread group * @param target the object whose run() method gets called * @param name the name of the new Thread * @param stackSize the desired stack size for the new thread, or * zero to indicate that this parameter is to be ignored. * @param acc the AccessControlContext to inherit, or * AccessController.getContext() if null * @param inheritThreadLocals if {@code true}, inherit initial values for * inheritable thread-locals from the constructing thread */帮我翻译一下
/**
* 初始化一个Thread。
*
* @param g 线程所属的线程组
* @param target 要调用其run()方法的对象
* @param name 新线程的名称
* @param stackSize 新线程的期望栈大小,或者为零以指示忽略此参数。
* @param acc 要继承的AccessControlContext,如果为null则使用AccessController.getContext()
* @param inheritThreadLocals 如果为true,则从构造线程继承可继承的线程本地变量的初始值。
*/