上一节讲到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会根据设定的顺序获取插件。

  1. public HystrixCommandExecutionHook getCommandExecutionHook() {
  2. //如果HystrixPlugins没有注册插件
  3. if (commandExecutionHook.get() == null) {
  4. //通过配置文件和查找类路径实现接口
  5. Object impl = getPluginImplementation(HystrixCommandExecutionHook.class);
  6. //如果没有实现自定义插件,使用默认插件
  7. if (impl == null) {
  8. commandExecutionHook.compareAndSet(null, HystrixCommandExecutionHookDefault.getInstance());
  9. } else {
  10. commandExecutionHook.compareAndSet(null, (HystrixCommandExecutionHook) impl);
  11. }
  12. }
  13. return commandExecutionHook.get();
  14. }
  15. private <T> T getPluginImplementation(Class<T> pluginClass) {
  16. T p = getPluginImplementationViaProperties(pluginClass, dynamicProperties);
  17. if (p != null) return p;
  18. return findService(pluginClass, classLoader);
  19. }
  20. private static <T> T getPluginImplementationViaProperties(Class<T> pluginClass, HystrixDynamicProperties dynamicProperties) {
  21. String classSimpleName = pluginClass.getSimpleName();
  22. String propertyName = "hystrix.plugin." + classSimpleName + ".implementation";
  23. String implementingClass = dynamicProperties.getString(propertyName, null).get();
  24. if (implementingClass != null) {
  25. ...
  26. Class<?> cls = Class.forName(implementingClass);
  27. cls = cls.asSubclass(pluginClass);
  28. return (T) cls.newInstance();
  29. ...
  30. } else {
  31. return null;
  32. }
  33. }
  34. private static <T> T findService(
  35. Class<T> spi,
  36. ClassLoader classLoader) throws ServiceConfigurationError {
  37. ServiceLoader<T> sl = ServiceLoader.load(spi,
  38. classLoader);
  39. for (T s : sl) {
  40. if (s != null)
  41. return s;
  42. }
  43. return null;
  44. }

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并初始化。

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

配置策略

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

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

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

并发策略

  并发策略可以让用户自定义实现线程池、请求作用域、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. @SuppressWarnings注解用法详解(转)

    原文连接https://blog.csdn.net/sysware_carol/article/details/52100580 今天来谈谈@SuppressWarnings注解的作用. J2SE 提 ...

  2. cinder migrate基础内容-源码分析

    一.cinder-api服务入口 D:\code-program\cinder-codejuno\api\contrib\admin_actions.py from cinder import vol ...

  3. webstorm激活码2020--定期更新

    2020年8月22日更新 一般错误关闭软件重填即可,key is invalid 错误需要恢复破解或者重装,才能使用 V8AF5QDT5R-eyJsaWNlbnNlSWQiOiJWOEFGNVFEVD ...

  4. 2020.5.23 第三篇 Scrum冲刺博客

    Team:银河超级无敌舰队 Project:招新通 项目冲刺集合贴:链接 目录 一.每日站立会议 二.项目燃尽图 三.签入记录 3.1 代码/文档签入记录 3.2 主要代码截图 3.3 程序运行截图 ...

  5. Dubbo详解

    什么是DubboDubbo是一个分布式服务框架,致力于提供高性能和透明化的远程服务调用方案,这容易和负载均衡弄混,负载均衡是对外提供一个公共地址,请求过来时通过轮询.随机等,路由到不同server.目 ...

  6. 0基础掌握接口测试神器-Postman

    一:Postman环境搭建 1:postman是什么?Postman是一款功能强大的网页调试与发送网页HTTP请求的接口测试工具.2:postman有几种安装方式?两种,应用程序和浏览器插件 3:po ...

  7. 关于C#.WinForm 与 WinApi的SendMessage 方法

    介绍: Windows Api 的 SendMessage 该函数将指定的消息发送到一个或多个窗口.此函数为指定的窗口调用窗口程序,直到窗口程序处理完消息再返回.而和函数PostMessage不同,P ...

  8. java23种设计模式——六、适配器模式

    @ 目录 介绍 应用场景 优缺点 模式实现 源码在我的github和gitee中获取 介绍 适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁.这种类型的设计模式属于结构型模 ...

  9. WPF新手快速入门系列 2.绑定

    [概要] 上一章讲了布局,按照市面上的书籍每一本讲的顺序都不一样,本系列是希望大家能快速上手去应对工作需要,所以本章就直接开始讲绑定. 如有学习过程中想交流学习.疑惑解答可以来此QQ群交流:58074 ...

  10. url_for函数——快速寻找url

    我们已经知道,知道了url就可以找到对应的视图函数,那么现在问题来了,如果我们知道了视图函数,要怎么找到url呢?这时候我们就需要url_for函数了. # coding: utf-8from fla ...