引入Hystrix Aspect
application-context.xml文件中
<aop:aspectj-autoproxy/>
<bean id="hystrixAspect" class="com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect"></bean>
<context:component-scan base-package="****"/>
<context:annotation-config/>
@HystrixCommand(groupKey = "PoiInfoServiceCommand", commandKey=“getStagedPoiBase”, fallbackMethod = "getStagedPoiBaseFallBack",
commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000"),//指定多久超时,单位毫秒。超时进fallback
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),//判断熔断的最少请求数,默认是10;只有在一个统计窗口内处理的请求数量达到这个阈值,才会进行熔断与否的判断
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),//判断熔断的阈值,默认值50,表示在一个统计窗口内有50%的请求处理失败,会触发熔断
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds" , value = "10000") //熔断多少毫秒后开始尝试请求 默认5000ms
},
threadPoolProperties = {
@HystrixProperty(name = "coreSize", value = "8"),
@HystrixProperty(name = "maxQueueSize", value = "100"),
@HystrixProperty(name = "keepAliveTimeMinutes", value = "2"),
@HystrixProperty(name = "queueSizeRejectionThreshold", value = "15"),
@HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "12"),
@HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "1440")
}
)
public List<PoiBaseTf> getStagedPoiBase(List<Long> poiIds) throws Exception{
//todo
}
/**
* fallback方法
*/
public List<PoiBaseTf> getStagedPoiBaseFallBack(List<Long> poiIds) {
//fallback逻辑
}
NOTICE:
-
需要hystrix感知(需要执行fallback且记入CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE统计)的异常都需要抛出来,否则如果所有的异常都catch住,发生异常时,hystrix无法感知,无法统计错误率。需要Hystrix忽略的异常,增加 @HystrixCommand(ignoreExceptions = {BadRequestException.class}即可,配置ignoreExceptions的异常不会统计到错误率里面。
-
groupKey与CommandKey无直接关系,我们可以简单的理解为,groupKey控制是否同一个线程池,commandKey控制是否同一个熔断器。
-
需要增加hystrix注解的方法必须为public,fallback方法可以为private。两者需要返回值和参数相同。
-
在类本身的其他方法中调用增加hystrix注解的方法,无法达到自动降级目的。
-
在fallback方法中不允许有远程方法调用,方法尽量要轻,调用其他外部接口也要进行hystrix降级。否则执行fallback方法会抛出异常。
Hystrix文档:https://github.com/Netflix/Hystrix/wiki
Hystrix-javanica文档:https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-javanica
Hystrix配置文档:https://github.com/Netflix/Hystrix/wiki/configuration