SpringCloud中如何使用Hystrix熔断器

本篇文章为大家展示了SpringCloud中如何使用Hystrix熔断器,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

一、简介

什么是Hystrix
  1. 单词本身意思就是断路器,发音 [hɪst'rɪks] ,怎么读听这里 https://www.koolearn.com/dict/wd_73657.html

  2. Hystrix是NetFlix公司开源的项目,提供了熔断器的功能,能够阻止分布式系统中出现的联动故障。

  3. Hystrix通过隔离服务的访问点阻止联动故障,并且提供故障解决方案,提高了分布式系统的弹性和容错。

Hystrix所解决的问题
  1. 防止服务故障导致资源耗尽。

    通过熔断机制,可以防止单个服务故障导致影响整个Servlet容器的线程资源。

  2. 避免过长等待。

    快速失败机制,如果某个服务故障,则接下来该服务不会处理请求,快速的返回失败。

  3. 增加服务弹性。

  • 提供了回退方案,请求发生故障时,可以调用fallback处理。

  • 提供熔断机制,防止故障传播到其他服务。

  • 熔断后不断尝试,特定条件下可以自动修复服务。

  • 提供监控。

    提供熔断器的监控组件 Hystrix Dashboard,可以实时监控断路器的状态。

  • 二、简单使用

    无论是Ribbon使用还是Feign使用,都需要前面两步

    1. pom.xml中增加依赖

    <!-- hystrix熔断器依赖 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-hystrix</artifactId>
    </dependency>
    1. 启动类增加注解表示开启熔断器功能

    @SpringBootApplication
    @EnableEurekaClient
    @EnableHystrix
    public class ServerApplication {
    
        private static final Logger logger = LoggerFactory.getLogger(ServerApplication.class);
    
        public static void main(String[] args) {
            SpringApplication.run(ServerApplication.class,args);
            logger.info("hystrix server start up finished !");
        }
    
    }
    Ribbon搭配使用
    @Autowired
    private RestTemplate restTemplate;
    
    /**
     * 每个需要熔断的远程方法上,增加注解,定义回调
     * @HystrixCommand定义服务降级,这里的fallbackMethod服务调用失败后调用的方法。
     * @return
     */
    @HystrixCommand(fallbackMethod = "hiError")
    public String getHi(){
        return restTemplate.getForObject("http://hystrix-service/hi", String.class);
    }
    
    /**
     * fallbackMethod指向此方法,表示远程调用失败后,快速的使用此方法替代
     */
    public String hiError(){
        return "error";
    }
    Fiegn搭配使用
    1. 在远程服务的FeignClient的注解上增加回调,定义回调类

    @FeignClient(value = "common-service", 
                 configuration = FeignConfiguration.class, 
                 fallback = RemoteCommonServiceCallback.class)
    public interface RemoteCommonServiceClient {
        /**
         * 调用远程方法
         * @return
         */
        @GetMapping(value = "/hello")
        String remoteCommonServiceHello();
    
    }
    1. 实现FeignClient中定义的回调类

    /**
     * <p>
     *   @Component注册为一个组件,实现RemoteCommonServiceClient,重写方法定义回调
     * <p>
     * @author Calvin
     * @date 2019/10/24
     * @since 1.0
     */
    @Component
    public class RemoteCommonServiceCallback implements RemoteCommonServiceClient {
    
        @Override
        public String remoteCommonServiceHello() {
            return "something error, this is callback";
        }
    }
    1. application.yml中开启Feign对Hystrix的支持

    feign:
      hystrix:
        enabled: true

    具体测试,可以通过停掉需要被调用的远程服务来测试,或者自己制造一些,服务在某段时间不可用,使线程睡眠等操作

    三、监控

    Hystrix Dashboard
    1. 增加依赖

    <!-- Springboot监控 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <!-- Hystrix Dashboard -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
    </dependency>
    1. 启动类增加注解开启dashboard

    /**
     * <p>
     *     启动类,集合了服务注册、FeignClient声明式调用、开启熔断器、开启熔断器监控
     * </p>
     *
     * @author Calvin
     * @date 2019/10/24
     * @since 1.0
     */
    @SpringBootApplication
    @EnableEurekaClient
    @EnableFeignClients
    @EnableHystrix
    @EnableHystrixDashboard
    public class HystrixServerApplication {
    
        private static final Logger logger = LoggerFactory.getLogger(HystrixServerApplication.class);
    
        public static void main(String[] args) {
            SpringApplication.run(HystrixServerApplication.class,args);
            logger.info("hystrix server start up finished !");
        }
    
    }
    1. 监控页面观察

    • step1:浏览器输入http://localhost:8080/hystrix SpringCloud中如何使用Hystrix熔断器

    • step2:页面填入 http://localhost:8080/hystrix.stream Dalay和Title自己填 SpringCloud中如何使用Hystrix熔断器

    • step3: 没有step3,以下是踩过的坑

    1. 地址栏输入的和页面填进去的东西一定不是同一个,输错了只能看到一直在ping,就像这样
      SpringCloud中如何使用Hystrix熔断器

    2. 刚进去的时候是loading状态的时候表着急,就像下图,你只需要调用一下远程服务
      SpringCloud中如何使用Hystrix熔断器

    3. 指标意义
      SpringCloud中如何使用Hystrix熔断器
      注:此图来源 https://blog.csdn.net/wm6752062/article/details/86136204 侵删

    Turbine聚合监控
    1. 新建服务turbine-monitor

    2. pom.xml

    <parent>
        <artifactId>hystrix-test</artifactId>
        <groupId>com.calvin.hystrix</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    
    <modelVersion>4.0.0</modelVersion>
    <artifactId>turbine-monitor</artifactId>
    
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-turbine</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    1. TurbineMonitorApplication

    /**
     * <p>
     *     启动类
     * </p>
     *
     * @author Calvin
     * @date 2019/10/24
     * @since
     */
    
    @SpringBootApplication
    @EnableTurbine
    @EnableHystrix
    @EnableHystrixDashboard
    public class MonitorApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(MonitorApplication.class,args);
        }
    
    }
    1. application.yml

    spring:
      application:
        name: turbine-monitor
    server:
      port: 8040
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:8010/eureka/
    turbine:
    # 需要监控的服务名
      app-config: common-service, hystrix-service
    # 服务名的集群
      cluster-name-expression: new String("default")
    1. 启动服务

    • 浏览器:http://localhost:8040/hystrix
      SpringCloud中如何使用Hystrix熔断器



    • 调用远程服务
      SpringCloud中如何使用Hystrix熔断器

    上述内容就是SpringCloud中如何使用Hystrix熔断器,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注行业资讯频道。