ITPub博客

首页 > 架构设计 > 软件结构 > (27)java Spring Cloud企业快速开发架构之SpringCloud-使用Hystrix实现容错处理

(27)java Spring Cloud企业快速开发架构之SpringCloud-使用Hystrix实现容错处理

原创 软件结构 作者:JIAN2 时间:2021-09-22 15:41:23 0 删除 编辑

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

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


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

推荐分布式架构源码

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

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


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

public String defaultCallHello() {
    return "fail";
}


只要不启动 8088 端口所在的服务,调用 /callHello 接口,就可以看到返回的内容是“fail”,如图 1 所示。

将启动类上的 @EnableHystrix 去掉,重启服务,再次调用 /callHello 接口可以看到返回的是 500 错误信息,这个时候就没有用到回退功能了。

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


配置详解
HystrixCommand 中除了 fallbackMethod 还有很多的配置,下面我们来看看这些配置,如下表所示:

HystrixCommand 配置详解

官方的配置信息文档请参考:https://github.com/Netflix/Hystrix/wiki/Configuration。

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

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

需要框架源码的朋友可以看我个人简介联系我 


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70006413/viewspace-2793042/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
华为资深架构师,曾参与华为数据中心迁移解决方案!有需要了解分布式微服务电商源码的朋友可以+我 v ❤: haiwabbc2 , 10余年互联网研发行业经验!博客里面是个人的一点技术总结,希望能够帮助到更多的IT朋友成长!

注册时间:2021-09-06

  • 博文量
    1404
  • 访问量
    622719