上一节讲到HystrixCommand的执行流程。

  Hystrix内部将一些模块实现成了插件,并且提供了用户提供自己的实现,通过配置来替换插件。Hystrix提供了5个插件,分别为并发相关插件(HystrixConcurrencyStrategy)、事件通知插件(HystrixEventNotifier)、度量信息插件(HystrixMetricsPublisher)Properties配置插件(HystrixPropertiesStrategy)、插件HystrixCommand回调函数类(HystrixCommandExecutionHook)。

  想要使用自定义的插件,需要实现相应接口,然后通过HystrixPlugins注册插件、或者通过配置配置自定义插件、或者将插件放在类路径。HystrixPlugins获取插件顺序:

  1.HystrixPlugins 会使用通过register注册的实现类。

  2.HystrixPlugins会去properties(HystrixDynamicProperties)配置下需找相应类型的实现类。

  3.通过ServiceLoader获取相应类型的实现类。

  4.使用默认实现类。

  本质原理是,Hystrix内部通过接口方式编程,具体实现通过HystrixPlugins获取。HystrixPlugins会根据设定的顺序获取插件。

public HystrixCommandExecutionHook getCommandExecutionHook() {
//如果HystrixPlugins没有注册插件
if (commandExecutionHook.get() == null) {
//通过配置文件和查找类路径实现接口
Object impl = getPluginImplementation(HystrixCommandExecutionHook.class);
//如果没有实现自定义插件,使用默认插件
if (impl == null) {
commandExecutionHook.compareAndSet(null, HystrixCommandExecutionHookDefault.getInstance());
} else {
commandExecutionHook.compareAndSet(null, (HystrixCommandExecutionHook) impl);
}
}
return commandExecutionHook.get();
}
private <T> T getPluginImplementation(Class<T> pluginClass) {
T p = getPluginImplementationViaProperties(pluginClass, dynamicProperties);
if (p != null) return p;
return findService(pluginClass, classLoader);
}
private static <T> T getPluginImplementationViaProperties(Class<T> pluginClass, HystrixDynamicProperties dynamicProperties) {
String classSimpleName = pluginClass.getSimpleName();
String propertyName = "hystrix.plugin." + classSimpleName + ".implementation";
String implementingClass = dynamicProperties.getString(propertyName, null).get();
if (implementingClass != null) {
...
Class<?> cls = Class.forName(implementingClass);
cls = cls.asSubclass(pluginClass);
return (T) cls.newInstance();
...
} else {
return null;
}
}
private static <T> T findService(
Class<T> spi,
ClassLoader classLoader) throws ServiceConfigurationError {
ServiceLoader<T> sl = ServiceLoader.load(spi,
classLoader);
for (T s : sl) {
if (s != null)
return s;
}
return null;
}

HystrixEventNotifier

  在HystrixCommand和HystrixObservableCommand执行过程中会触发一些事件,实现HystrixEventNotifier可以监听这些事件进行一些告警和数据收集。

EMIT 当发射一个返回数据时,发送该消息,HystrixCommand不会发送该消息
SUCCESS 当发射一个返回数据时,发送该消息。
FAILURE  
TIMEOUT 发生time out异常时,发送该类型消息
BAD_REQUEST 发生bad request异常时,发送该类型消息
SHORT_CIRCUITED 熔断异常时,发送该类型消息
THREAD_POOL_REJECTED 处理线程池拒绝异常时,发送该类型消息
SEMAPHORE_REJECTED 处理信号量拒绝异常时,发送该类型消息
FALLBACK_EMIT 当fallback发射一个返回数据时,发送该消息,HystrixCommand不会发送该消息
FALLBACK_SUCCESS 当fallback执行结束时,发送该消息。
FALLBACK_FAILURE 当fallback执行异常并且异常不为UnsupportedOperationException时,发送该消息。
FALLBACK_REJECTION 当fallback执行超过指定并发量被拒绝时,发送该消息。
FALLBACK_MISSING 当fallback执行异常并且异常为UnsupportedOperationException时,发送该消息。
EXCEPTION_THROWN 当执行命令或fallback出现异常时,发送该消息
RESPONSE_FROM_CACHE 从缓存中获取结果时,发送该类型消息
CANCELLED  
COLLAPSED 当创建一个新的批量执行命令时,发送该类型消息

HystrixCommandExecutionHook

  在HystrixCommand和HystrixObservableCommand执行过程中会调用HystrixCommandExecutionHook的相应方法,通过实现HystrixCommandExecutionHook可以在HystrixCommand或HystrixObservableCommand执行期间的响应阶段进行回调。

方法 调用点
onStart HystrixInvokable执行前被调用
onEmit whenever the HystrixInvokable emits a value
onError if the HystrixInvokable fails with an exception
onSuccess iHystrixInvokable执行成功
onThreadStart at the start of thread execution if the HystrixInvokable is a HystrixCommand executed using the THREADExecutionIsolationStrategy
onThreadComplete at the completion of thread execution if the HystrixInvokable is a HystrixCommand executed using the THREAD ExecutionIsolationStrategy
onExecutionStart when the user-defined execution method in the HystrixInvokable begins
onExecutionEmit whenever the user-defined execution method in the HystrixInvokable emits a value
onExecutionError when the user-defined execution method in the HystrixInvokable fails with an exception
onExecutionSuccess when the user-defined execution method in the HystrixInvokable completes successfully
onFallbackStart if the HystrixInvokable attempts to call the fallback method
onFallbackEmit whenever the fallback method in the HystrixInvokableemits a value
onFallbackError if the fallback method in the HystrixInvokable fails with an exception or does not exist when a call attempt is made
onFallbackSuccess if the fallback method in the HystrixInvokable completes successfully
onCacheHit if the response to the HystrixInvokable is found in the HystrixRequestCache
onUnsubscribe  

Metrics发布

  通过实现HystrixMetricsPublisher可以获取所有实例的metrics信息,这样我们就可以获取和存储这些metrics信息,以便后续处理。默认的实现不会发布这些metrics信息。

  在创建AbstractCommand,HystrixThreadPoolDefault,HystrixObservableCollapser时分别会通过HystrixPlugins获取HystrixMetricsPublisherCommand,HystrixMetricsPublisherThreadPool,HystrixMetricsPublisherCollapser并初始化。

protected AbstractCommand(HystrixCommandGroupKey group, HystrixCommandKey key, HystrixThreadPoolKey threadPoolKey, HystrixCircuitBreaker circuitBreaker, HystrixThreadPool threadPool,
HystrixCommandProperties.Setter commandPropertiesDefaults, HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults,
HystrixCommandMetrics metrics, TryableSemaphore fallbackSemaphore, TryableSemaphore executionSemaphore,
HystrixPropertiesStrategy propertiesStrategy, HystrixCommandExecutionHook executionHook) {
...
HystrixMetricsPublisherFactory.createOrRetrievePublisherForCommand(this.commandKey, this.commandGroup, this.metrics, this.circuitBreaker, this.properties);
...
}
public HystrixThreadPoolDefault(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties.Setter propertiesDefaults) {
this.properties = HystrixPropertiesFactory.getThreadPoolProperties(threadPoolKey, propertiesDefaults);
...
HystrixMetricsPublisherFactory.createOrRetrievePublisherForThreadPool(threadPoolKey, this.metrics, this.properties);
}
HystrixObservableCollapser(HystrixCollapserKey collapserKey, Scope scope, CollapserTimer timer, HystrixCollapserProperties.Setter propertiesBuilder, HystrixCollapserMetrics metrics) {
... HystrixMetricsPublisherFactory.createOrRetrievePublisherForCollapser(collapserKey, this.metrics, properties);
...
}

配置策略

  配置策略的作用是提供Hystrix配置信息。

  在创建AbstractCommand,HystrixThreadPoolDefault,HystrixObservableCollapser时分别会通过HystrixPropertiesStrategy获取HystrixCommandProperties,HystrixThreadPoolProperties,HystrixCollapserProperties并初始化。

private static HystrixCommandProperties initCommandProperties(HystrixCommandKey commandKey, HystrixPropertiesStrategy propertiesStrategy, HystrixCommandProperties.Setter commandPropertiesDefaults) {
if (propertiesStrategy == null) {
return HystrixPropertiesFactory.getCommandProperties(commandKey, commandPropertiesDefaults);
} else {
// used for unit testing
return propertiesStrategy.getCommandProperties(commandKey, commandPropertiesDefaults);
}
}
public HystrixThreadPoolDefault(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties.Setter propertiesDefaults) {
this.properties = HystrixPropertiesFactory.getThreadPoolProperties(threadPoolKey, propertiesDefaults);
...
}
HystrixObservableCollapser(HystrixCollapserKey collapserKey, Scope scope, CollapserTimer timer, HystrixCollapserProperties.Setter propertiesBuilder, HystrixCollapserMetrics metrics) {
...
HystrixCollapserProperties properties = HystrixPropertiesFactory.getCollapserProperties(collapserKey, propertiesBuilder);
...
}

并发策略

  并发策略可以让用户自定义实现线程池、请求作用域、Callable。

hystrix(8) 插件的更多相关文章

  1. 使用Hystrix的插件机制,解决在使用线程隔离时,threadlocal的传递问题

    背景 在我们的项目中,比较广泛地使用了ThreadLocal,比如,在filter层,根据token,取到用户信息后,就会放到一个ThreadLocal变量中:在后续的业务处理中,就会直接从当前线程, ...

  2. hystrix文档翻译之插件

    插件 可以通过实现插件来改变Hystrix的行为.可以通过HystrixPlugins来注册自定义插件,这些插件会被应用到HystrixCommand,HystrixObservableCommand ...

  3. hystrix源码之插件

    HystrixPlugins 获取并发相关类(HystrixConcurrencyStrategy).事件通知类(HystrixEventNotifier).度量信息类(HystrixMetricsP ...

  4. Spring Cloud入门教程-Hystrix断路器实现容错和降级

    简介 Spring cloud提供了Hystrix容错库用以在服务不可用时,对配置了断路器的方法实行降级策略,临时调用备用方法.这篇文章将创建一个产品微服务,注册到eureka服务注册中心,然后我们使 ...

  5. spring cloud: Hystrix(三):健康指数 health Indicator

    spring cloud: Hystrix(三):健康指数 health Indicator ribbon+hystrix 当使用Hystrix时(spring-cloud-starter-hystr ...

  6. 服务容错保护断路器Hystrix之四:断路器监控(Hystrix Dashboard)-turbine集群监控

    turbine 英[ˈtɜ:baɪn] n. 汽轮机; 涡轮机; 透平机; OK,上文我们看了一个监控单体应用的例子,在实际应用中,我们要监控的应用往往是一个集群,这个时候我们就得采取Turbine集 ...

  7. 服务容错保护断路器Hystrix之三:断路器监控(Hystrix Dashboard)-单体监控

    turbine:英 [ˈtɜ:baɪn] 美 [ˈtɜ:rbaɪn] n.汽轮机;涡轮机;透平机 一.Hystrix Dashboard简介 在微服务架构中为了保证程序的可用性,防止程序出错导致网络阻 ...

  8. 服务容错保护断路器Hystrix之二:Hystrix工作流程解析

    一.总运行流程 当你发出请求后,hystrix是这么运行的 红圈 :Hystrix 命令执行失败,执行回退逻辑.也就是大家经常在文章中看到的“服务降级”. 绿圈 :四种情况会触发失败回退逻辑( fal ...

  9. 服务容错保护断路器Hystrix之一:入门示例介绍(springcloud引入Hystrix的两种方式)

    限流知识<高可用服务设计之二:Rate limiting 限流与降级> 在微服务架构中,我们将系统拆分成了一个个的服务单元,各单元间通过服务注册与订阅的方式互相依赖.由于每个单元都在不同的 ...

随机推荐

  1. SpringBoot 集成SpringSecurity JWT

    目录 1. 简介 1.1 SpringSecurity 1.2 OAuth2 1.3 JWT 2. SpringBoot 集成 SpringSecurity 2.1 导入Spring Security ...

  2. GAN量化评估方法——IS(Inception Score)和FID(Frechet Inception Distance score)

    生成模型产生的是高维的复杂结构数据,它们不同于判别模型,很难用简单的指标来评估模型的好坏.下面介绍两种当前比较流行的评估生成模型的指标(仅判别图像):IS(Inception Score)和FID(F ...

  3. 已废弃_CSDN慕零的黑夜-头条-第一期(必问)[导读:]1.CSDN必问赏金流向何方 2.CSDN必问偷偷做的手脚 3.CSDN必问靠谱吗 4.关于钱于回答的平衡问题:一美元拍卖骗局qq3461896724

    [本文有已知的链接差错,懒得改了] 本期是关于CSDN 必问 (biwen.csdn.net)的内容,欢迎评论文末,文中插入有 小姐姐 img(附py代码,1.49G) + coding资料 哟~~~ ...

  4. Jenkins配置总结

    1.配置全局 系统管理->全局工具配置 2.配置 自己安装安装jdk,git,以及maven 3.系统管理->系统配置 3.1配置Jenkins URL 3.2 配置SSH Servers ...

  5. PC,移动端H5实现实现小球加入购物车效果

    HTML部分: <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" ...

  6. nova 通过 python curl 创建虚拟机---keystone v2

    #! /bin/python #coding=utf- import urllib2 import json import requests # token post_url = 'http://12 ...

  7. MySQL数据库根据一个或多个字段查询重复数据

    系统在开发测试过程中出现bug,比如并发操作没有处理好,数据库中往往会插入重复数据,这些脏数据经常会导致各种问题.bug可以修改,但是数据往往也要处理,处理SQL如下: 1.根据一个字段查找重复数据 ...

  8. Qt启动子进程,子进程关闭时通知主进程,实现主进程对子进程的管理

    自己开发了一个股票智能分析软件,功能很强大,需要的点击下面的链接获取: https://www.cnblogs.com/bclshuai/p/11380657.html 1.需求描述  Qt主进程启动 ...

  9. akka-grpc - 应用案例

    上期说道:http/2还属于一种不算普及的技术协议,可能目前只适合用于内部系统集成,现在开始大面积介入可能为时尚早.不过有些项目需求不等人,需要使用这项技术,所以研究了一下akka-grpc,写了一篇 ...

  10. WPF Devexpress ChartControl CrosshairLabel显示内容居右

    源码可加Q群:580749909. 一.解决的问题 ChartControl中希望CrosshairLabel的内容据右 or 自定义 二.实现. 多个显示实例(实例:条形,线形,点等等)下的内容设置 ...