image.png

image.png

船新版本:

image.png

在消费者controller的方法上添加image.png注解
image.png
image.png当提供服务的生产者出故障(例如关掉它),默认超时时间是1000毫秒,过了这个时间就触发熔断器,消费者无法访问生产者就返回error

添加 hystrix 起步依赖

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
  4. </dependency>

主程序添加 @EnableCircuitBreaker 启用 hystrix 断路器

启动断路器,断路器提供两个核心功能:

  • 降级,超时、出错、不可到达时,对服务降级,返回错误信息或者是缓存数据
  • 熔断,当服务压力过大,错误比例过多时,熔断所有请求,所有请求直接降级
  • 可以使用 @SpringCloudApplication 注解代替三个注解

    RibbonController 中添加降级方法

  • 为每个方法添加降级方法,例如 getItems() 添加降级方法 getItemsFB()

  • 添加 @HystrixCommand 注解,指定降级方法名

    1. @GetMapping("/item-service/{orderId}")
    2. @HystrixCommand(fallbackMethod = "getItemsFB") //指定降级方法的方法名
    3. public JsonResult<List<Item>> getItems(@PathVariable String orderId) {
    4. return rt.getForObject("http://item-service/{1}", JsonResult.class, orderId);
    5. }

    hystrix 超时设置

    hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds
    hystrix等待超时后, 会执行降级代码, 快速向客户端返回降级结果, 默认超时时间是1000毫秒
    为了测试 hystrix 降级,我们把 hystrix 等待超时设置得非常小(500毫秒)
    此设置一般应大于 ribbon 的重试超时时长,例如 10 秒
  1. hystrix:
  2. command:
  3. default:
  4. execution:
  5. isolation:
  6. thread:
  7. timeoutInMilliseconds: 500

springcloud-hystirx - 图10