springcloud-Hystrix-降级fallback

一般要进行降级的情况可以分为:调用方异常 和 被调用方异常

   被调用方的降级保护,步骤如下:

  1.在方法上添加@HystrixCommand注解,设置当该方法异常时指定哪个方法作为反馈,还可设置本方法的超时时间,具体如下:

    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })
    public String paymentInfo_TimeOut(Integer id) {

        int timeNumber = 4000;
//         int timeNumber = 10/0;
        try {
            TimeUnit.MILLISECONDS.sleep(timeNumber);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池: " + Thread.currentThread().getName() + " PaymenyInfo_TimeOut,id: " + id + "	" + "O(∩_∩)O哈哈~" + " 耗时" + timeNumber + "毫秒";
    }

    public String paymentInfo_TimeOutHandler(Integer id) {
        return "线程池: " + Thread.currentThread().getName() + " 8001系统繁忙系统报错,请稍后再试id: " + id + "	" + "( Ĭ ^ Ĭ )";
    }

  2.在主启动加上@EnableCircuitBreaker,表示激活Hystrix的注解

@EnableCircuitBreaker
public class HystrixPaymentApplication {

  调用方的降级保护,这个也是最常见的,一般降级保护大多用在调用方,步骤和上面一样,不过多了一个配置,如下:

  1.在方法上添加@HystrixCommand注解

  2.在主启动加上@EnableCircuitBraker

  3.在application.yml加上如下配置:

feign:
  hystrix:
    enabled: true

   对了,要是修改了@HystrixCommand注解的属性,最好重启微服务,因为有时不生效

原文地址:https://www.cnblogs.com/ibcdwx/p/14438065.html