Hystrix

一、Command执行过程

下图简单罗列的一个请求(即我们包装的Command)在Hystrix内部被执行的关键过程。

二、创建Command对象源码

这一过程也包含了策略、资源的初始化,参看AbstractCommand的构造函数:

protected AbstractCommand(...) {
    // 初始化group,group主要是用来对不同的command key进行统一管理,比如统一监控、告警等
    this.commandGroup = initGroupKey(...);
    // 初始化command key,用来标识降级逻辑,可以理解成command的id
    this.commandKey = initCommandKey(...);
    // 初始化自定义的降级策略
    this.properties = initCommandProperties(...);
    // 初始化线程池key,相同的线程池key将公用线程池
    this.threadPoolKey = initThreadPoolKey(...);
    // 初始化监控器
    this.metrics = initMetrics(...);
    // 初始化断路器
    this.circuitBreaker = initCircuitBreaker(...);
    // 初始化线程池
    this.threadPool = initThreadPool(...);
 
    // Hystrix通过SPI实现了插件机制,允许用户对事件通知、处理和策略进行自定义
    this.eventNotifier = HystrixPlugins.getInstance().getEventNotifier();
    this.concurrencyStrategy = HystrixPlugins.getInstance().getConcurrencyStrategy();
    HystrixMetricsPublisherFactory.createOrRetrievePublisherForCommand(this.commandKey, this.commandGroup, this.metrics, this.circuitBreaker, this.properties);
    this.executionHook = initExecutionHook(executionHook);
 
    this.requestCache = HystrixRequestCache.getInstance(this.commandKey, this.concurrencyStrategy);
    this.currentRequestLog = initRequestLog(this.properties.requestLogEnabled().get(), this.concurrencyStrategy);
 
    /* fallback semaphore override if applicable */
    this.fallbackSemaphoreOverride = fallbackSemaphore;
 
    /* execution semaphore override if applicable */
    this.executionSemaphoreOverride = executionSemaphore;
}

Command对象是有状态的(比如每次请求参数可能不同),所以每次请求都需要新创建Command,这么多初始化工作,如果并发量过高,会不会带来过大的系统开销?其实构造函数中的很多初始化工作只会集中在创建第一个Command时来做,后续创建的Command对象主要是从静态Map中取对应的实例来赋值,比如监控器、断路器和线程池的初始化,因为相同的Command的command key和线程池key都是一致的,在HystrixCommandMetrics、HystrixCircuitBreaker.Factory、HystrixThreadPool中会分别有如下静态属性:

private static final ConcurrentHashMap<String, HystrixCommandMetrics> metrics = new ConcurrentHashMap<String, HystrixCommandMetrics>();
 
private static ConcurrentHashMap<String, HystrixCircuitBreaker> circuitBreakersByCommand = new ConcurrentHashMap<String, HystrixCircuitBreaker>();
 
final static ConcurrentHashMap<String, HystrixThreadPool> threadPools = new ConcurrentHashMap<String, HystrixThreadPool>();

可见所有Command对象都可以在这里找到自己对应的资源实例。

参考文献

版权声明:本文为CSDN博主「飞向札幌的班机」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/manzhizhen/article/details/80296655

原文地址:https://www.cnblogs.com/frankcui/p/15245165.html