Hystrix(自定义的实现 熔断,降级)

创建类继承 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()方法,熔断策略(报错或则超时或则违背自定义策略触发)。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值