使用Hystrix实现自动降级与依赖隔离
??
原文链接:http://www.jianshu.com/p/138f92aa83dc 1.背景目前对于一些非核心操作,如增减库存后保存操作日志 发送异步消息时(具体业务流程),一旦出现MQ服务异常时,会导致接口响应超时,因此可以考虑对非核心操作引入服务降级、服务隔离。 2.Hystrix说明官方文档 [https://github.com/Netflix/Hystrix/wiki]
2.1为什么需要Hystrix?在大中型分布式系统中,通常系统很多依赖(HTTP,hession,Netty,Dubbo等),在高并发访问下,这些依赖的稳定性与否对系统的影响非常大,但是依赖有很多不可控问题:如网络连接缓慢,资源繁忙,暂时不可用,服务脱机等。 当依赖阻塞时,大多数服务器的线程池就出现阻塞(BLOCK),影响整个线上服务的稳定性,在复杂的分布式架构的应用程序有很多的依赖,都会不可避免地在某些时候失败。高并发的依赖失败时如果没有隔离措施,当前应用服务就有被拖垮的风险。 例如:一个依赖30个SOA服务的系统,每个服务99.99%可用。 99.99%的30次方 ≈ 99.7% 0.3% 意味着一亿次请求 会有 3,000,00次失败 换算成时间大约每月有2个小时服务不稳定. 随着服务依赖数量的变多,服务不稳定的概率会成指数性提高. 解决问题方案:对依赖做隔离。 2.2Hystrix设计理念想要知道如何使用,必须先明白其核心设计理念,Hystrix基于命令模式,通过UML图先直观的认识一下这一设计模式
image.png
可见,Command是在Receiver和Invoker之间添加的中间层,Command实现了对Receiver的封装。那么Hystrix的应用场景如何与上图对应呢? API既可以是Invoker又可以是reciever,通过继承Hystrix核心类HystrixCommand来封装这些API(例如,远程接口调用,数据库查询之类可能会产生延时的操作)。就可以为API提供弹性保护了。 2.3Hystrix如何解决依赖隔离
2.4Hystrix流程结构解析
image.png
流程说明: 1:每次调用创建一个新的HystrixCommand,把依赖调用封装在run()方法中. 2:执行execute()/queue做同步或异步调用. 3:判断熔断器(circuit-breaker)是否打开,如果打开跳到步骤8,进行降级策略,如果关闭进入步骤. 4:判断线程池/队列/信号量是否跑满,如果跑满进入降级步骤8,否则继续后续步骤. 5:调用HystrixCommand的run方法.运行依赖逻辑 5a:依赖逻辑调用超时,进入步骤8. 6:判断逻辑是否调用成功 6a:返回成功调用结果 6b:调用出错,进入步骤8. 7:计算熔断器状态,所有的运行状态(成功,失败,拒绝,超时)上报给熔断器,用于统计从而判断熔断器状态. 8:getFallback()降级逻辑. 以下四种情况将触发getFallback调用: (1):run()方法抛出非HystrixBadRequestException异常。 (2):run()方法调用超时 (3):熔断器开启拦截调用 (4):线程池/队列/信号量是否跑满 8a:没有实现getFallback的Command将直接抛出异常 8b:fallback降级逻辑调用成功直接返回 8c:降级逻辑调用失败抛出异常 9:返回执行成功结果 2.5熔断器:Circuit Breaker每个熔断器默认维护10个bucket,每秒一个bucket,每个bucket记录成功,超时,拒绝的状态, 默认错误超过50%且10秒内超过20个请求进行中断拦截.
image.png
2.6Hystrix隔离分析Hystrix隔离方式采用线程/信号的方式,通过隔离限制依赖的并发量和阻塞扩散.
image.png
3.接入方式本文会重点介绍基于服务化项目(thrift服务化项目)的接入方式。 3.1添加hystrix依赖
<hystrix-version>1.4.22</hystrix-version> <dependency> <groupId>com.netflix.hystrix</groupId> <artifactId>hystrix-core</artifactId> <version>${hystrix-version}</version> </dependency> <dependency> <groupId>com.netflix.hystrix</groupId> <artifactId>hystrix-metrics-event-stream</artifactId> <version>${hystrix-version}</version> </dependency> <dependency> <groupId>com.netflix.hystrix</groupId> <artifactId>hystrix-javanica</artifactId> <version>${hystrix-version}</version> </dependency> <dependency> <groupId>com.netflix.hystrix</groupId> <artifactId>hystrix-servo-metrics-publisher</artifactId> <version>${hystrix-version}</version> </dependency> <dependency> <groupId>com.meituan.service.us</groupId> <artifactId>hystrix-collector</artifactId> <version>1.0-SNAPSHOT</version> </dependency> 3.2引入Hystrix Aspectapplication-context.xml文件中 <aop:aspectj-autoproxy/> <bean id="hystrixAspect" class="com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect"></bean> <context:component-scan base-package="com.***.***"/> <context:annotation-config/>
3.3统计数据需要注册plugin,直接从plugin中获取统计数据 新增初始化Bean import com.meituan.service.us.collector.notifier.CustomEventNotifier; import com.netflix.hystrix.contrib.servopublisher.HystrixServoMetricsPublisher; import com.netflix.hystrix.strategy.HystrixPlugins; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; /** * Created by gaoguangchao on 16/7/1. */ public class HystrixMetricsInitializingBean { private static final Logger LOGGER = LoggerFactory.getLogger(HystrixMetricsInitializingBean.class); public void init() throws Exception { LOGGER.info("HystrixMetrics starting..."); HystrixPlugins.getInstance().registerEventNotifier(CustomEventNotifier.getInstance()); HystrixPlugins.getInstance().registerMetricsPublisher(HystrixServoMetricsPublisher.getInstance()); } } application-context.xml文件中 <bean id="hystrixMetricsInitializingBean" class="com.***.HystrixMetricsInitializingBean" init-method="init"/> 3.4添加注解本文使用同步执行方式,因此注解及方法实现都为同步方式,如果有异步执行、反应执行的需求,可以参考:官方注解说明[https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-javanica] @HystrixCommand(groupKey = "productStockOpLog",commandKey = "addProductStockOpLog",fallbackMethod = "addProductStockOpLogFallback",commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "400"),//指定多久超时,单位毫秒。超时进fallback @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//判断熔断的最少请求数,默认是10;只有在一个统计窗口内处理的请求数量达到这个阈值,才会进行熔断与否的判断 @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",//判断熔断的阈值,默认值50,表示在一个统计窗口内有50%的请求处理失败,会触发熔断 } ) public void addProductStockOpLog(Long sku_id,Object old_value,Object new_value) throws Exception { if (new_value != null && !new_value.equals(old_value)) { doAddOpLog(null,null,sku_id,ProductOpType.PRODUCT_STOCK,old_value != null ? String.valueOf(old_value) : null,String.valueOf(new_value),"C端",null); } } public void addProductStockOpLogFallback(Long sku_id,Object new_value) throws Exception { LOGGER.warn("发送商品库存变更消息失败,进入Fallback,skuId:{},oldValue:{},newValue:{}",old_value,new_value); } 示例: @HystrixCommand(groupKey="UserGroup",commandKey = "GetUserByIdCommand", commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "100"),//指定多久超时,单位毫秒。超时进fallback @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",//判断熔断的最少请求数,默认是10;只有在一个统计窗口内处理的请求数量达到这个阈值,才会进行熔断与否的判断 @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",//判断熔断的阈值,默认值50,表示在一个统计窗口内有50%的请求处理失败,会触发熔断 },threadPoolProperties = { @HystrixProperty(name = "coreSize",value = "30"),@HystrixProperty(name = "maxQueueSize",value = "101"),@HystrixProperty(name = "keepAliveTimeMinutes",value = "2"),@HystrixProperty(name = "queueSizeRejectionThreshold",value = "15"),@HystrixProperty(name = "metrics.rollingStats.numBuckets",value = "12"),@HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds",value = "1440") }) 说明: hystrix函数需要放在一个service中,并且,在类本身的其他函数中调用hystrix函数,是无法达到监控的目的的。 3.5参数配置
4.参数说明其他参数可参见 https://github.com/Netflix/Hystrix/wiki/Con
5.性能测试5.1测试情况
image.png
去除Cold状态的第一个异常点后,1-10测试场景的Hystrix平均耗时如上图所示, 可以得出结论:
本文首发在 高广超的简书博客 转载请注明! 作者:高广超 链接:http://www.jianshu.com/p/138f92aa83dc 來源:简书 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |