美文网首页
四、SpringCloud 之 Hystrix 框架入门

四、SpringCloud 之 Hystrix 框架入门

作者: cqzhangjian | 来源:发表于2018-09-12 11:23 被阅读0次

生活中的空气开关设备,当电路发生短路等情况的时候,空气开关设备就会立刻断开电流,保障用电火灾的发生。Hystrix 框架就是实现了类似于 空气开关设备的作用,在多应用程序上级联依赖过程中,级联依赖的某个组件不可用的时候, 就可以使用 Hystrix 来断开依赖,避免整个系统的不可用。起到服务的保护功能。

1.Hystrix 介绍

1.1 Hystrix 概述

Hystrix 的使用提供了 访问调用远程系统、 服务以及第三方的节点出现的延迟或者故障的容错能力

1.2 Hystrix 弹性容器性特点

  • 在一定条件下,Hystrix 能够自动打开和关闭,通过三种状态(打开、关闭、半开)作为依据。
  • 断路器的开关由关闭到打开的状态,是通过当前服务健康状况 和设定阀值比较决定的。
  • 服务健康状态:请求服务失败数量/请求服务次数
  • 设定阀值 :默认时间范围内故障的次数
  • 断路器关闭时,请求允许通过断路器,当服务健康状态高于阀值,保持断路器关闭状态。反之亦然
  • 断路器打开时,请求禁止通过断路器,当设置fallback 方法,则进入fallback流程
  • 断路器半打开时,运行 一个请求进入断路器,如果该请求调用成功,断路器就恢复到关闭状态,反之保持到打开状态

fallback 流程给 服务不可用的情况下可以给用户一个提示,这种避免了其他服务崩溃问题

2.Hystrix 使用

2.1 创建 服务注册中心工程

2.2 创建 服务提供者工程 (横向扩展两个实例)

2.3 创建 服务调用者工程 (使用 熔断器)

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

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

    @SpringBootApplication
    @EnableEurekaClient
    @EnableCircuitBreaker  //开启断路器功能
    public class ScServiceOrderInvokeApplication {

    
      @Bean
      @LoadBalanced
      public RestTemplate restTemplate() {
        
        return new RestTemplate();
      }
    
    
      public static void main(String[] args) {
        SpringApplication.run(ScServiceOrderInvokeApplication.class, args);
      }
    }


============================================================================
@RestController
public class InvokeOrderServerController {

    @Autowired
    RestTemplate testTemplate;
    
    
    @GetMapping(value="/api/invoke/order/{id}")
    @HystrixCommand(fallbackMethod="fallbackInfo") // 指定 fallback逻辑的回调方法名称
    public String getOrderInfo(@PathVariable String id) {
        return testTemplate.getForObject("http://sc-service-order/order/"+id, String.class);
    }
    
    // 回调方法
    public String fallbackInfo(@PathVariable String id) {
        
        return "服务不可以用,稍后再试..";
    }
    
    
}
注意: 回调方法和接口方法参数和返回值必须保持一致

2.4 源代码下载地址

https://github.com/cqzhangjian/eureka-hystrix.git

相关文章

网友评论

      本文标题:四、SpringCloud 之 Hystrix 框架入门

      本文链接:https://www.haomeiwen.com/subject/fhqvgftx.html