LD is tigger forever,CG are not brothers forever, throw the pot and shine.
Modesty is not false, solid is not naive, treacherous but not deceitful, stay with good people, and stay away from poor people.
talk is cheap, show others the code,Keep progress,make a better result.
目录
概述
创建类继承 HystrixCommand类实现里面的方法:
架构特性
@Component
public class HystrixFallback<T> extends HystrixCommand<T>{
private Object cla;// 方法对象
private Object[] args; //参数
private String mname;//方法名
private Class[] patms;// 参数类型
public HystrixFallback() {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("FallbackGroup"))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(5000)));
}
public HystrixFallback(Object cla,String mname,Class[] patms ,Object ... args) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(cla.getClass().getName()))
.andThreadPoolPropertiesDefaults( // 配置线程池
HystrixThreadPoolProperties.Setter()
.withCoreSize(10) // 配置线程池里的线程数,设置足够多线程,以防未熔断却打满threadpool
)
.andCommandPropertiesDefaults( // 配置熔断器
HystrixCommandProperties.Setter()
.withCircuitBreakerEnabled(true) // 熔断器在整个统计时间内是否开启的阀值
.withCircuitBreakerRequestVolumeThreshold(3) // 至少有3个请求才进行熔断错误比率计算
.withCircuitBreakerErrorThresholdPercentage(50) //当出错率超过50%后熔断器启动
.withMetricsRollingStatisticalWindowInMilliseconds(5000) // 统计滚动的时间窗口
.withExecutionTimeoutInMilliseconds(3000) //熔断超时时间
.withCircuitBreakerSleepWindowInMilliseconds(2000) // 熔断器工作时间,超过这个时间,先放一个请求进去,成功的话就关闭熔断,失败就再等一段时间
));
this.cla = cla;
this.args=args;
this.mname=mname;
this.patms=patms;
}
@Override
public T run() throws Exception {
Class[] argsClass = null;
if(patms!=null && patms.length>0){
argsClass=patms;
}else{
argsClass= new Class[args.length];
for (int i = 0, j = args.length; i < j; i++) {
argsClass[i] = args[i].getClass();
}
}
Class<? extends Object> cs = cla.getClass();
Method menthod = cs.getMethod(mname,argsClass);
Object temp = menthod.invoke(cla,args);
return (T) temp;
}
@Override
public T getFallback() {
System.err.println("熔断");
//throw new SessionMissAccountException();
return null;
}
}
设计思路
1.通过泛型实现不同类的调用,通过反射调用方法,实现。
2.配置熔断器线程池,以及熔断器规则。
3.实现run(需要熔断的调用方法)主体方法,实现getFallback()方法,熔断策略(报错或则超时或则违背自定义策略触发)。
实现思路分析
相关工具如下:
实验效果:(解决思路)
分析:
小结:
主要讲述了一些Hystrix实现自定义接口降级,里面有许多不足,请大家指正~
参考资料和推荐阅读
1.链接: 参考资料.