Hystrix断路器的入门使用

  • POM文件中添加
 <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
                <version>2.2.2.RELEASE</version>
            </dependency>
  • 主启动类添加@EnableCircuitBreaker或者@EnableHystrix
  • 使用一:在需要服务降级的接口上添加@HystrixCommand 指定 fallbackMethod 方法
	@GetMapping("/payment/hystrix/timeout/{id}")
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOut_fallback",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")  //3秒钟以内就是正常的业务逻辑
    })
    public String paymentInfo_TimeOut(@PathVariable("id") Integer id){

        int a = 10/id;
		int b = 5; //方法执行五秒,超时
        try {
            TimeUnit.SECONDS.sleep(b);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        return "线程池:"+Thread.currentThread().getName()+"----"+a+"";
    }


    public String paymentInfo_TimeOut_fallback(Integer id){
        return "线程池:"+Thread.currentThread().getName()+"我来兜底了";
    }
  • 使用二 Feign使用Hystrix
    在@FeignClient上添加fallback属性指定兜底的类,这个类实现这个接口,实现的方法就是兜底的方法

@Service
@FeignClient(value = "cloud-payment-service",fallback = PaymentServiceFallback.class)
public interface PaymentService {

    @GetMapping("/payment/hystrix/timeout/{id}")
    public String paymentInfo_TimeOut(@PathVariable("id") Integer id);

}

@Service
class PaymentServiceFallback implements PaymentService{

    @Override
    public String paymentInfo_TimeOut(Integer id) {
        return "兜底方法----paymentInfo_TimeOut"+"对方服务异常";
    }
}

重点:要想使用这种方式,必须在配置文件中添加

#feign使用hystrix开启服务熔断
feign:
  hystrix:
    enabled: true #如果处理自身的容错就开启。
  • 方式三 @DefaultProperties设置全局兜底方法
@RestController
@Slf4j
@DefaultProperties(defaultFallback = "payment_Global_FallbackMethod")  //全局的
public class PaymentController {

    @GetMapping("/payment/hystrix/timeout/{id}")
    @HystrixCommand  //这个注解不能少
    public String paymentInfo_TimeOut(@PathVariable("id") Integer id){
        int a = 10/id;
        return "线程池:"+Thread.currentThread().getName()+"----"+a+"";
    }

	//必须是无参方法
    public String payment_Global_FallbackMethod(){
        return "线程池:"+Thread.currentThread().getName()+"我来兜底了,我是全局兜底";
    }
}

注意这里的全局兜底方法不能有参数

参考文件:https://www.jianshu.com/p/8e577d8c1b20

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值