Springcloud~openfeign開啟hystrix基于線程池熔斷的傳值問題
我們都知道,在hystrix默認情況下,采用線程池的熔斷方式,每個openfeign都有自己的線程,而這使得它無法獲取主線程上的變量;現在有個現實的問題就是,當前端登錄后,把token經過gateway傳到服務A,服務A再調用服務B時,B是無法收到請求頭里的token信息的;一種不太好的解決方案就是使用信號量的方式。

使用ThreadLocal存儲變量
public class NextHttpHeader {
static final InheritableThreadLocal<Map<String, String>> inheritableThreadLocal = new InheritableThreadLocal<>();
public static void set(String key, String val) {
if (inheritableThreadLocal.get() == null) {
inheritableThreadLocal.set(MapUtils.<String, String>hashMapBuilder(8).put(key, val).build());
} else {
inheritableThreadLocal.get().put(key, val);
}
}
public static String get(String key) {
if (inheritableThreadLocal.get() == null) {
return null;
}
return inheritableThreadLocal.get().get(key);
}
public static Set<String> get() {
if (inheritableThreadLocal.get() == null) {
return null;
}
return inheritableThreadLocal.get().keySet();
}
}
繼承HystrixConcurrencyStrategy抽象類,實現自己的賦值邏輯
public class RequestContextHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy {
public <T> Callable<T> wrapCallable(Callable<T> callable) {
// 先包裝一下要執行的任務,在這里把ThreadLocal的值取出來
return new ThreadLocalCallable<T>(callable);
}
public static class ThreadLocalCallable<V> implements Callable<V> {
private Callable<V> target;
private Map<String, String> dic = new HashMap<>();
public ThreadLocalCallable(Callable<V> target) {
this.target = target;
NextHttpHeader.get().forEach(o -> {
this.dic.put(o, NextHttpHeader.get(o));
});
}
@Override
public V call() throws Exception {
this.dic.keySet().forEach(o -> {
NextHttpHeader.set(o, this.dic.get(o));
});
return target.call();
}
}
}
注冊
@Configuration
@Slf4j
public class HystrixCircuitBreakerConfiguration {
@PostConstruct
public void init() {
HystrixPlugins.getInstance().registerConcurrencyStrategy(new RequestContextHystrixConcurrencyStrategy());
}
}
發現openFeign請求時,將變量放到請求頭
/**
* 基于openFeign的攔截器,處理需要向下游傳遞的信息.
*
* @author lind
* @date 2023/1/29 11:44
* @since 1.0.0
*/
@Configuration
public class FeignTraceIdInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate template) {
if (NextHttpHeader.get() != null) {
NextHttpHeader.get().forEach(o -> {
template.header(o, NextHttpHeader.get(o));
});
}
}
}
spring中的口子太多,太靈活,需要不斷的去找那個最優雅,最正確的方法
浙公網安備 33010602011771號