Skip to content

Instantly share code, notes, and snippets.

@yp-palF
Last active October 2, 2019 15:14
Show Gist options
  • Save yp-palF/d97a4b6554e728176b20f9037b26313a to your computer and use it in GitHub Desktop.
Save yp-palF/d97a4b6554e728176b20f9037b26313a to your computer and use it in GitHub Desktop.
public class HystrixHook extends HystrixCommandExecutionHook {
private HystrixRequestVariableDefault<Integer> hrv = new HystrixRequestVariableDefault<>();
@Override
public <T> void onStart(HystrixInvokable<T> commandInstance) {
HystrixRequestContext.initializeContext();
getThreadLocals();
}
@Override
public <T> void onExecutionStart(HystrixInvokable<T> commandInstance) {
setThreadLocals();
}
@Override
public <T> void onFallbackStart(HystrixInvokable<T> commandInstance) {
setThreadLocals();
}
@Override
public <T> void onSuccess(HystrixInvokable<T> commandInstance) {
HystrixRequestContext.getContextForCurrentThread().shutdown();
super.onSuccess(commandInstance);
}
@Override
public <T> Exception onError(HystrixInvokable<T> commandInstance, HystrixRuntimeException.FailureType failureType, Exception e) {
HystrixRequestContext.getContextForCurrentThread().shutdown();
return super.onError(commandInstance, failureType, e);
}
private void getThreadLocals() {
hrv.set(ThreadLocalUtil.getId());
}
private void setThreadLocals() {
ThreadLocalUtil.setId(hrv.get());
}
}
// Register hystrix hook plugin
HystrixPlugins.getInstance().registerCommandExecutionHook(new HystrixHook());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment