Hystrix介绍
>Hystrix is a latency and fault tolerance library designed to isolate points of access to remote systems, services and 3rd party libraries, stop cascading failure and enable resilience in complex distributed systems where failure is inevitable.
github-Hystrix
Hystrix 主要用于服务调用的隔离,容错,降级处理,在分布式系统中,调用多个服务,而单个服务出现问题会导致系统级联出错,发生雪崩效应。同时提供dashboard实时监控。
Hystrix 隔离机制
Hystrix 提供两种隔离机制
THREAD:线程池模式,通过使用单个线程池来进行服务隔离,支持超时,大多数场景都应该使用这个,比如rpc调用。
SEMAPHORE:信号量模式,通过获取信号量的方式进行限流,比如经典的秒杀,只允许几个进程进入。
关于这两种模式的区别:两种机制的区别
Hystrix 设计模式
Hystrix 使用 Command 模式进行设计,关于Command 模式,请查看设计模式 ( 十三 ) 命令模式Command(对象行为型)
Hystrix 配置
Hystrix 默认使用Archaius 进行配置管理,一共提供四个级别, 分别是 默认属性 < 动态全局默认属性< 实例属性(写在代码中的)< 动态配置实例属性。
并通过后台线程去定时读取动态配置信息。
Archaius实现的自定义扩展代码:
//实现 配置策略 public class DBConfigurationSource implements PolledConfigurationSource { // ... @Override public PollResult poll(boolean initial, Object checkPoint) throws Exception { // implement logic to retrieve properties from DB } } //实现调度更新策略 public class MyScheduler extends AbstractPollingScheduler { // ... @Override protected synchronized void schedule(Runnable runnable) { // schedule the runnable } @Override public void stop() { // stop the scheduler } } //最后注册生效 DynamicConfiguration configuration = new DynamicConfiguration(source, scheduler); ConfigurationManager.install(configuration);
我们这篇博客主要就是介绍怎么实现动态配置实例属性,可以根据上面的策略实现自己的更新方式,比如存储至redis等等,下面介绍两种方式。
配置文件方式
Hystrix 默认会从 classpath:config.property 中去读取属性值来实现动态配置,比如
// 其中的CommandKey对应自己的配置 hystrix.command.CommandKey.execution.isolation.thread.timeoutInMilliseconds=20000 hystrix.command.CommandKey.fallback.isolation.semaphore.maxConcurrentRequests=200 hystrix.command.CommandKey.circuitBreaker.enabled=true hystrix.command.CommandKey.circuitBreaker.requestVolumeThreshold=30
所以可以通过修改该配置文件,来实现动态更新。
该配置文件的位置也可以修改
-Darchaius.configurationSource.additionalUrls=http://myserver/properties
zookeeper 动态更新方式
更新的流程和上面提到的方式一样,我们使用zookeeper的动态配置功能。 项目和说明都放在github上了
zookeeper 实现hystrix动态配置