notice_hystrix增加hystrix实现错误熔断(配置文件方式)

说明

在 notice 工程中 增加 hystrix,当 getNoticeById() 响应超时、报错时,会调用 fallback() 返回响应

修改pom.xml

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

修改主启动类

增加下面注解:

@EnableHystrix

修改 Controller

修改 getNoticeById() 方法,增加熔断注解
为了模拟报错,当传入id是1时就抛异常:

@GetMapping(value="/getNoticeById/{id}")
@HystrixCommand(fallbackMethod = "fallback")
public CommonResult<Notice> getNoticeById(@PathVariable("id") String id){
    Notice notice=noticeService.getNoticeById(id);
    System.out.println("=====id:"+id+"--"+new Date());

    if("1".equals(id)) {//当id是1时就抛错
        int i = 1 / 0;
    }

    try {
        Thread.sleep(3000);//休眠3秒,表示复杂运算、查询数据库等 耗时操作
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    return new CommonResult(200,"成功!",notice);
}

增加 fallback 方法

public CommonResult<Notice> fallback(@PathVariable("id") String id){
    return new CommonResult(100,"服务熔断");
}

注意:

  1. fallback() 方法 返回值 必须与 熔断方法 相同(如果有泛型,泛型也要相同)
  2. fallback() 方法 参数列表 必须与 熔断方法 相同

修改 application.yml

hystrix:
  command:
    default:
      execution:
        timeout:
          enable: true #为false则超时控制有ribbon控制,为true则hystrix超时和ribbon超时都用,但是谁小谁生效,默认为true
        isolation:
          thread:
            timeoutInMilliseconds: 2000 #熔断器的超时时长默认1秒,时间太短,业务还没完成就容易触发超时熔断

      circuitBreaker:
        requestVolumeThreshold: 10
        sleepWindowInMilliseconds: 20000
        errorThresholdPercentage: 50

参数解释: 详见hystrix熔断相关参数说明

测试

报错

访问:http://localhost:8081/getNotice/1 报错

连续访问超过10次以上,就会发现控制台不再打印信息,说明触发熔断,不再执行 getNoticeById 方法,而是直接执行 fallback 方法

此时访问:http://localhost:8081/getNotice/195c6547e5044c759dc39caf317998c5 ,即使不会触发错误,也直接执行 fallback 方法

直到进入下一个窗口期时,才会慢慢恢复,调用 getNoticeById 方法