将Spring RequestAttributes(RequestContextHolder)传播到Feign配置bean?

问题描述 投票:0回答:1

我正在使用Feign配置类,使用类似的注释声明;

@FeignClient(name = "${earfsdf}", configuration = FeignConf.class)

在这种情况下,FeignConf不是Spring @Configuration,它使用上面的注释纯粹为这个Feign客户端设定范围。在FeignConf中,我声明了一个RequestInterceptor bean;

@Bean
public RequestInterceptor requestInterceptor() {

这可以通过Feign正确获取,并且当我在Feign客户端上发出请求时会调用它。

但是,我希望这个RequestInterceptor bean能够访问Spring“RequestAttributes”,我试图使用Spring的RequestContextHolder.getRequestAttributes()获取它

似乎当我从RequestInterceptor中调用它时,它返回null。有没有什么方法可以将RequestAttributes传播到Feign RequestInterceptor中?

谢谢!

spring spring-cloud spring-cloud-feign feign
1个回答
0
投票

所以事实证明,答案是使用HystrixCallableWrapper,它允许你包装一个通过Hystrix的任务(我正在使用Feign)

Hystrix为Feign调用创建一个新线程。在父线程上调用可调用包装器,因此您可以获取所需的所有上下文,将其传递给新的可调用对象,然后将上下文加载到在新线程上执行的可调用对象内。

public class ContextAwareCallableWrapper implements HystrixCallableWrapper {

  @Override
  public <T> Callable<T> wrapCallable(Callable<T> callable) {

    Context context = loadContextFromThisThread();

    return new ContextAwareCallable<>(callable, context);
  }

  public static class ContextAwareCallable<T> implements Callable<T> {

    private final Callable<T> callable;
    private Context context;

    ContextAwareCallable(Callable<T> callable, Context context) {
      this.callable = callable;
      this.context = context;
    }

    @Override
    public T call() throws Exception {

      try {
        loadContextIntoNewThread(context);
        return callable.call();
      } finally {
        resetContext();
      }
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.