迁移到 Spring-boot-2.0 并启用java.lang.IllegalStateException的 Spring 执行器后,尝试注册 hystrix 并发策略失败,指出"另一个策略已经注册"。尽管我没有在我的代码中的任何其他地方使用registerConcurrencyStrategy。
我想注册并发策略以结转日志 MDC 上下文,以便我能够同样很好地记录 Hystrix 包装方法(包括线程局部变量)内部和外部。这曾经在 spring-boot-1.5 中完美运行
迁移到 spring-boot 2.0(从 1.5 版本)后,HystrixPlugins.getInstance().registerConcurrencyStrategy(this);失败并显示 IllegalStateException
根据 https://github.com/Netflix/Hystrix/issues/1057,如果(a)任何其他代码流在调用之前都会注册自己的或默认的ConcurrencyStrategy(b)在调用之前通过Hystrix进行任何调用,则可能会出现此问题
由于上述调用位于用 @Component 注释的类的构造函数中,因此理想情况下应在发生任何方法调用之前调用它(其他 bean 的初始化除外,包括它们的构造函数)。
在调用SpringApplication.run(MyApplication.class, args) 之前,我们甚至尝试在 SpringBoot Application Class 的主方法中移动这段代码;但这也没有用。
@Component
public class ContextCopyHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy {
private static final String EVENT = "HystrixConcurrencyStrategy";
private static final String ACTION = "ContextCopy";
public ContextCopyHystrixConcurrencyStrategy(Logger logger, LoggerUtil defaultLoggerUtil) {
try {
HystrixPlugins.getInstance().registerConcurrencyStrategy(this);
} catch (IllegalStateException e) {
defaultLoggerUtil.logEvents(logger, Level.WARN, e.getMessage(), EVENT, ACTION, "", "Race condition! Could not register strategy. HystrixConcurrencyStrategy is already initialized.");
}
预期:我的注册应该在任何其他代码之前发生,并且注册应该成功
实际:我的注册失败,出现非法状态异常
如何确保我的注册在任何其他注册之前发生(我的代码中不存在,但可能位于我可能传递使用的某些库中)
默认情况下,Spring boot 2 累加器注册Hystrix Metric Binder be,这些 beder会重置已经设置的 HystrixConcurrencyStrategy 并设置 HystrixConcurrencyStrategyDefault。 因此,禁用该豆子
management.metrics.binders.hystrix.enabled=false
将有助于不重置您的自定义 HystrixConcurrencyStrategy
我们仔细查看了我的 maven .m2 目录类,并在所有 jar 中的所有类中查找registerConcurrencyStrategy。我们发现
io.micrometer.core.instrument.binder.hystrix
在内部注册了默认的HystrixConcurrencyStrategy。
经过进一步的研究,我们发现在application.properties中设置以下属性:management.metrics.binders.hystrix.enabled=false禁用了 Hystrix Metrics Binder(我实际上不确定它的作用!),然后事情就解决了
我正在使用 spring-boot-starter-parent v2.5.3 和 Spring Cloud 版本 2020.0.3。
我不得不手动包含spring-cloud-starter-netflix-hystrix的版本。启动微服务时,我收到"另一个策略已注册"异常。我包括
management.metrics.binders.hystrix.enabled=false
在application.properties
文件中,此问题已解决。