Hystrix熔断降级的实现

  1. 引入Hystrix依赖
<dependency>
                <groupId>com.netflix.hystrix</groupId>
                <artifactId>hystrix-core</artifactId>
                <version>1.5.18</version>
</dependency>
  1. 自定义一个Service,加上@Service注解。建议再添加一个@Slf4j注解,用于日志打印
  2. 创建一个内部类,继承HystrixCommand<响应结果体>
  3. 具体实现
@Service
@Slf4j
public class HystrixService {

    public HystrixResp request(String url, HystrixReq req) {
        CommonHystrixCommand commonHystrixCommand = new CommonHystrixCommand(url, req);
        HystrixResp resp = commonHystrixCommand.execute();
        return resp;
    }

    private class CommonHystrixCommand extends HystrixCommand<HystrixResp> {

        private String url;

        private HystrixReq req;

        CommonHystrixCommand(String url, HystrixReq req) {
            super(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("msgRptGroup"))
                    .andCommandKey(HystrixCommandKey.Factory.asKey("msgRpt"))
                    .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("msgRptPool"))
                    .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
                            .withCoreSize(200)
                            .withMaximumSize(200))
                    .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                            // 命令执行的超时时间
                            .withExecutionTimeoutInMilliseconds(2000)
                            // 断路器打开后的休眠窗口时间,在此时间后,断路器会尝试再次允许请求
                            .withCircuitBreakerSleepWindowInMilliseconds(5000)
                            // 当错误率超过20%时,断路器将打开
                            .withCircuitBreakerErrorThresholdPercentage(20)
                            // 在最近的10的请求中,如果满足上面的错误率阈值,断路器才会打
                            .withCircuitBreakerRequestVolumeThreshold(10)
                            // 允许的最大并发回退请求数量为20
                            .withFallbackIsolationSemaphoreMaxConcurrentRequests(20)));
            this.url = url;
            this.req = req;
        }

        @Override
        protected HystrixResp run() throws Exception {
            HystrixResp resp = HttpClient.post(url, req, HystrixResp.class);
            return resp;
        }

        @Override
        protected HystrixResp getFallback() {
            log.warn("Hystrix fallback");
            PerfCounter.setMeterCount("getFallback", 1L, "reportUrl=" + reportUrl);
            HystrixResp resp = new HystrixResp();
            resp.setCode(0);
            resp.setMsg("fallback");
            return resp;
        }
    }
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值