notice_hystrix增加hystrix实现错误熔断(注解方式)

说明

可通过注解方式,针对每一个方法设置参数

修改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",commandProperties = {
        @HystrixProperty(name="circuitBreaker.enabled",value="true"),
        @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
        @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="20000"),
        @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value="50"),
})
public JsonResult<Notice> getNoticeById(@PathVariable("id") String id){
    logger.info("id:"+id);
    if("1".equals(id)) {//当id是1时就抛错
        int i = 1 / 0;
    }
    Notice notice=noticeService.getNoticeById(id);
    JsonResult res=new JsonResult(200,"成功!");
    res.setData(notice);

    return res;
}

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

增加 fallback 方法

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

注意:

  1. fallback方法 返回值 必须与 熔断方法 相同(如果有泛型,泛型也要相同)
  2. fallback方法 参数列表 必须与 熔断方法 相同
  3. 尽量把熔断添加再最外层的方法中

测试

报错

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

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

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

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