Hystrix是Netflix针对微服务分布式系统的熔断保护中间件,当我们的客户端连接远程的微服务时,有两种情况需要考虑:首先,如果远程系统当机了我们怎么办?其次,我们如何管理对远程微服务的调用性能,以保证每个微服务以最小延迟最快性能响应?
Hystrix是一个有关延迟和失败容错的开源库包,用来设计隔离访问远程系统端点或微服务等,防止级联爆炸式的失败,也就是由一个小问题引起接二连三扩大的疯狂的错误爆炸直至整个系统瘫痪,能够让复杂的分布式系统更加灵活具有弹性。
废话不多说,直接上代码
步骤1、pom文件增加Hystrix依赖
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-core</artifactId>
<version>1.5.1</version>
</dependency>
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-javanica</artifactId>
<version>1.5.1</version>
</dependency>
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-metrics-event-stream</artifactId>
<version>1.5.1</version>
</dependency
步骤2、引入HystrixCommandAspect切面,对HystrixCommand和HystrixCollapser进行拦截
<bean id="hystrixAspect" class="com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect"/>
步骤3、加载本地Hystrix文件
@Service
public class HystrixInitConfiguration implements InitializingBean {
private static Logger logger = LoggerFactory.getLogger(HystrixInitConfiguration.class);
@Override
public void afterPropertiesSet() throws Exception {
PropertiesConfiguration hystrixConfig = new PropertiesConfiguration();
try{
System.setProperty(DynamicPropertyFactory.ENABLE_JMX,"true");
hystrixConfig.load("hystrix.properties");
ConfigurationManager.install(hystrixConfig);
}catch (ConfigurationException e){
throw new IllegalArgumentException("载入hystrix.properties失败,请检查配置!"+e.getMessage(),e);
}catch (Exception e){
throw new IllegalArgumentException("安装hystrix配置项目失败。" + e.getMessage(), e);
}
}
}
步骤4、本地Hystrix配置文件
# hystrix configuration
# see https://github.com/Netflix/Hystrix/wiki/Configuration
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=10000
hystrix.threadpool.default.coreSize=10
hystrix.command.default.circuitBreaker.requestVolumeThreshold=20
hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds=5
hystrix.command.default.circuitBreaker.errorThresholdPercentage=50
hystrix.command.default.circuitBreaker.forceOpen=false
hystrix.command.default.circuitBreaker.forceClosed=false
hystrix.threadpool.queryPool.coreSize=20
hystrix.command.queryCommand.execution.isolation.thread.timeoutInMilliseconds=2000
步骤5、代码中引入Hystrix监控
@HystrixCommand(commandKey = "queryCommand",threadPoolKey = "queryPool")
public Map<String, String> query(QueryParam param) {
}
这里设置的熔断机制是
timeout 2s熔断 并发超20熔断