我有一个获得带有授权标头的http请求的服务. 在处理请求时,我想使用Feign Client查询其他服务.对其他服务的查询应包含相同的授权标头.
I have a service that gets http request with an authorization header. When processing the request, I want to use a Feign Client to query another service. The query to the other service should include the same authorization header.
当前,我使用过滤器从传入的请求中提取授权标头,并将标头存储在ThreadLocal中. 构建Feign Client时,我使用RequestInterceptor从ThreadLocal读取授权标头,并将其放入对其他服务的请求中.
Currently I use a Filter to extract the authorization header from the incoming request, store the header in a ThreadLocal. When building the Feign Client I use a RequestInterceptor to read the authorization header from the ThreadLocal and put it into the request to the other service.
这种方法并不理想,因为当我开始使用RxJava或Hystrix之类的东西时,在处理请求时会更改线程,并且我必须将授权标头ThreadLocal从一个线程移动到另一个线程.
This approach is not ideal, because when I start using things like RxJava or Hystrix, threads are changed while processing the request and I have to move the authorization header ThreadLocal from one thread to another.
还有其他解决方案吗? 我正在考虑的一种方法是为每个请求创建一个新的FeignClient,这样我就不再需要将授权存储在本地线程中.但这是个好主意吗?
What are other options to solve this? One way that I am thinking about is to create a new FeignClient for each request, this way I would no longer need to store the authorization in a thread local. But is this a good idea?
推荐答案我认为我找到了解决问题的方法.使用RequestContextHolder,我可以获取对原始请求的引用(也来自生成的子线程),并从那里复制标头:
I think I found a solution for my problem. Using RequestContextHolder I can get a reference to the original request (also from spawned child threads) and copy the header from there:
public class AuthForwardInterceptor implements RequestInterceptor { @Override public void apply(RequestTemplate template) { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); template.header(HttpHeaders.AUTHORIZATION, request.getHeader(HttpHeaders.AUTHORIZATION)); } }更多推荐
伪装客户
发布评论