Skip to content

Instantly share code, notes, and snippets.

@guozi
Created December 18, 2018 07:36
Show Gist options
  • Save guozi/6bee7880cca50c1e8fb60eeddb3d132e to your computer and use it in GitHub Desktop.
Save guozi/6bee7880cca50c1e8fb60eeddb3d132e to your computer and use it in GitHub Desktop.
Hystrix and MDC
/**
* Hystrix线程池隔离支持日志链路跟踪
*
* @author yuhao.wang3
*/
public class MdcHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy {
@Override
public <T> Callable<T> wrapCallable(Callable<T> callable) {
return new MdcAwareCallable(callable, MDC.getCopyOfContextMap());
}
private class MdcAwareCallable<T> implements Callable<T> {
private final Callable<T> delegate;
private final Map<String, String> contextMap;
public MdcAwareCallable(Callable<T> callable, Map<String, String> contextMap) {
this.delegate = callable;
this.contextMap = contextMap != null ? contextMap : new HashMap();
}
@Override
public T call() throws Exception {
try {
MDC.setContextMap(contextMap);
return delegate.call();
} finally {
MDC.clear();
}
}
}
}
@Configuration
public class HystrixConfig {
//用来拦截处理HystrixCommand注解
@Bean
public HystrixCommandAspect hystrixAspect() {
return new HystrixCommandAspect();
}
@PostConstruct
public void init() {
HystrixPlugins.getInstance().registerConcurrencyStrategy(new MdcHystrixConcurrencyStrategy());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment