增加消息绑定类
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;import org.springframework.web.context.request.RequestAttributes;import org.springframework.web.context.request.RequestContextHolder;import java.util.concurrent.Callable;/** * 此类能够保证:RequestContext请求上下文,也就是RequestAttributes能够在线程池里自动有效 */public class RequestContextHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy { // 这个时候还在主线程了,所以通过RequestContextHolder.getRequestAttributes()是能拿到上下文的 // 拿到后hold住,等到run执行的时候再绑定即可
@override public <T> Callable<T> wrapCallable(Callable<T> callable) { return new RequestAttributeAwareCallable<>(callable, RequestContextHolder.getRequestAttributes()); } static class RequestAttributeAwareCallable<T> implements Callable<T> { private final Callable<T> delegate; private final RequestAttributes requestAttributes; public RequestAttributeAwareCallable(Callable<T> callable, RequestAttributes requestAttributes) { this.delegate = callable; this.requestAttributes = requestAttributes; } // 执行之前绑定上下文,执行完成后释放 @Override public T call() throws Exception { try { RequestContextHolder.setRequestAttributes(requestAttributes); return delegate.call(); } finally { RequestContextHolder.resetRequestAttributes(); } } }}
在fegin的配置类中初始化插件类
@PostConstructpublic void plugin(){ HystrixPlugins.getInstance().registerConcurrencyStrategy(new RequestContextHystrixConcurrencyStrategy());}
在需要获取请求头信息的地方使用
public static String getToken() { ServletRequestAttributes requestAttributes = requestAttributes(); if (requestAttributes != null) { return requestAttributes.getRequest().getHeader("Authorization"); } return null;}private static ServletRequestAttributes requestAttributes() { return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();}