如果您希望某些线程本地上下文传播到@HystrixCommand中,默认的声明将不起作用,因为它在线程池中执行该命令(以防超时)。您可以使用一些配置,或者直接在注解中使用与调用者相同的线程,通过要求它使用不同的“隔离策略”。例如:

@HystrixCommand(fallbackMethod = "stubMyService",
    commandProperties = {
      @HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE")
    }
)
...

如果使用@SessionScope或@RequestScope,该方法也同样适用。你会知道什么时候你需要这么做因为一个运行时异常说它不能找到作用域的上下文。
您还可以设置hystrix.shareSecurityContext属性为true。这样做将自动配置一个Hystrix并发策略插件钩子,它将把安全上下文从主线程转移到Hystrix命令使用的一个线程。Hystrix不允许多个Hystrix并发策略注册这样一种扩展机制可以通过声明自己HystrixConcurrencyStrategy为Spring bean。Spring Cloud将在Spring上下文中查找它的实现,并将其封装到自己的插件中。

英文原文:
13.2 Propagating the Security Context or using Spring Scopes
If you want some thread local context to propagate into a @HystrixCommand the default declaration will not work because it executes the command in a thread pool (in case of timeouts). You can switch Hystrix to use the same thread as the caller using some configuration, or directly in the annotation, by asking it to use a different “Isolation Strategy”. For example:

@HystrixCommand(fallbackMethod = “stubMyService”,
commandProperties = {
@HystrixProperty(name=”execution.isolation.strategy”, value=”SEMAPHORE”)
}
)

The same thing applies if you are using @SessionScope or @RequestScope. You will know when you need to do this because of a runtime exception that says it can’t find the scoped context.

You also have the option to set the hystrix.shareSecurityContext property to true. Doing so will auto configure an Hystrix concurrency strategy plugin hook who will transfer the SecurityContext from your main thread to the one used by the Hystrix command. Hystrix does not allow multiple hystrix concurrency strategy to be registered so an extension mechanism is available by declaring your own HystrixConcurrencyStrategy as a Spring bean. Spring Cloud will lookup for your implementation within the Spring context and wrap it inside its own plugin.

分享到: 更多