hystrix文档翻译之插件

插件

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

插件类型

  • 事件通知

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

  • 发布metrics

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

  • 配置策略

  通过实现HystrixPropertiesStrategy可以改变配置的默认实现。系统默认使用Archaius. 

  • 并发策略

  Hystrix实现ThreadLocal,Callable,Runnable,ThreadPoolExecutor和BlockingQueue来实现线程隔离和请求作用域。

  Hystrix默认已经实现了这些功能,也提供了插件让用户通过实现HystrixConcurrencyStrategy可以实现自定义的组件:

  getThreadPool和getBlockingQueue方法可以让你实现自定义的线程池和队列。

  wrapCallable方法可以让你对Callable进行处理,

  getRequestVarible方法实现一个请求作用域。

  • HystrixCommandExecutionHook

   通过实现HystrixCommandExecutionHook可以在HystrixCommand或HystrixObservableCommand执行期间的响应阶段进行回调。

HystrixCommandExecutionHookmethodwhen Hystrix calls the method
onStart before the HystrixInvokable begins executing
onEmit whenever the HystrixInvokable emits a value
onError if the HystrixInvokable fails with an exception
onSuccess if the HystrixInvokable completes successfully
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

怎么使用

  当我们第一次使用HystrixCommand时,他就会初始化插件,所以我们不能在运行时来定义自定义组件。如果我们通过Archaius注册了组件,Hystrix会使用注册的组件,如果没有,会使用默认的组件。

  也可以在调用HystrixCommand之前,通过下面的语句注册组件

HystrixPlugins.getInstance().registerEventNotifier(ACustomHystrixEventNotifierDefaultStrategy.getInstance());

接口还是虚拟类

  我们通常通过继承虚拟类而不是接口来实现组件功能,有一下两个原因:

  • 默认实现

  通过虚拟类,只需要实现想要自定义的方法,并且可以重用默认的实现。每一个方法都是相互独立,并且不会互相影响。

  • 架包维护

  随着Hystrix的发展,这些插件可能会增加一些新的方法和功能,那么用户在更新时必须定制实现这些方法和功能。如果使用接口来实现插件,那么每次hystrix增加新的插件功能时,用户必须增加这些实现。在java8中可以在接口中定义默认方法,但是之前的并不行。所以通过实现虚拟类可以避免这样的情况。

原文地址:https://www.cnblogs.com/zhangwanhua/p/8117006.html