openfeign拦截器
配置拦截器需要实现 RequestInterceptor
接口
@Slf4j
public class FeignRequestInterceptor implements RequestInterceptor {
public static final String TRACE_ID = "TRACE_ID";
@Override
public void apply(RequestTemplate requestTemplate) {
String traceId = TraceIdUtil.getTraceId();
log.info("拦截器获取 traceId = {} ", traceId );
if(traceId != null){
requestTemplate.header(TRACE_ID,traceId);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
如果项目中使用了熔断器 Hystrix
, 并且使用的是线程池模式,就会导致无法从ThreadLocal获取到参数,必须做下包装
@Component
public class CustomizedHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy {
public CustomizedHystrixConcurrencyStrategy () {
HystrixPlugins.reset();
HystrixPlugins.getInstance().registerConcurrencyStrategy(this);
}
@Override
public <T> Callable<T> wrapCallable(Callable<T> callable) {
Map<String, String> map = MDC.getCopyOfContextMap();
return () -> {
try {
MDC.setContextMap(map);
return callable.call();
} finally {
MDC.clear();
}
};
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
上次更新: 2023/09/12, 10:37:04