notice_hystrix增加hystrix实现超时熔断(未完废弃)

说明

本文通过配置文件方式,实现超时熔断

修改 notice_hystrix 工程

修改pom.xml

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

修改主启动类

增加下面注解:

@EnableHystrix

修改 Controller

修改 getNoticeById() 方法,增加熔断注解
为了演示效果,当传入id是1时就休眠1.5秒:

@GetMapping(value="/getNoticeById/{id}")
@HystrixCommand(fallbackMethod = "fallback")
public JsonResult<Notice> getNoticeById(@PathVariable("id") String id){
    logger.info("id:"+id);
    if("1".equals(id)) {
        try {
            Thread.sleep(2500);//休眠
        } catch (InterruptedException e) {
//            e.printStackTrace();//注释掉此行,否则会打印错误
        }
    }
    Notice notice=noticeService.getNoticeById(id);
    JsonResult res=new JsonResult(200,"成功!");
    res.setData(notice);

    return res;
}

增加 fallback 方法

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

注意:

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

修改 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

注意: 由于 getNoticeById 休眠了2.5秒,超过配置文件中的 2 秒,会触发服务降级(超时达到一定次数才会触发熔断)

修改 ums_hystrix 工程

修改 application.yml

由于 notice_hystrix 超时时间是 2 秒触发降级,所以 ums_hystrix 工程要增加 hystrix 超时时间,要超过 2 秒,ums_hystrix 的服务降级就会触发

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 3000

测试

报错

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

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

此时访问:http://localhost:8081/getNotice/195c6547e5044c759dc39caf317998c5 也是直接执行 fallback 方法

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