创建一个新的 Maven 项目 hystrix-feign-demo,增加 Hystrix 的依赖,代码如下所示。

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

在启动类上添加 @EnableHystrix 或者 @EnableCircuitBreaker。注意,@EnableHystrix 中包含了 @EnableCircuitBreaker。

然后编写一个调用接口的方法,在上面增加一个 @HystrixCommand 注解,用于指定依赖服务调用延迟或失败时调用的方法,代码如下所示。

  1. @GetMapping("/callHello")
  2. @HystrixCommand(fallbackMethod = "defaultCallHello")
  3. public String callHello() {
  4. String result = restTemplate.getForObject("http://localhost:8088/house/hello", String.class);
  5. return result;
  6. }

当调用失败触发熔断时会用 defaultCallHello 方法来回退具体的内容,定义 default-CallHello 方法的代码如下所示。

  1. public String defaultCallHello() {
  2. return "fail";
  3. }

只要不启动 8088 端口所在的服务,调用 /callHello 接口,就可以看到返回的内容是“fail”,如图 1 所示。
image.png
将启动类上的 @EnableHystrix 去掉,重启服务,再次调用 /callHello 接口可以看到返回的是 500 错误信息,这个时候就没有用到回退功能了。

  1. {
  2. code: 500,
  3. message: "I/O error on GET request for
  4. "http://localhost:8088/house/hello": Connection refused; nested
  5. exception is java.net.ConnectException: Connection refused
  6. ", data:
  7. null
  8. }

配置详解

HystrixCommand 中除了 fallbackMethod 还有很多的配置,下面我们来看看这些配置,如下表所示:
image.png
image.pngimage.png
官方的配置信息文档请参考:https://github.com/Netflix/Hystrix/wiki/Configuration

上面列出来的都是 Hystrix 的配置信息,那么在 Spring Cloud 中该如何使用呢?只需要在接口的方法上面使用 HystrixCommand 注解(如下代码所示),指定对应的属性即可。

  1. @HystrixCommand(fallbackMethod = "defaultCallHello",commandProperties = {
  2. @HystrixProperty(name="execution.isolation.strategy", value = "THREAD")
  3. }
  4. )
  5. @GetMapping("/callHello")
  6. public String callHello() {
  7. String result = restTemplate.getForObject("http://localhost:8088/house/hello", String.class);
  8. return result;
  9. }