Spring Cloud 集成 Hystrix 熔断器

Hystrix 熔断器

Hystrix 概述

  • Hystrix 是 Netflix 开源的一个延迟和容错库,用于隔离访问远程服务、第三方库,防止出现级联失败(雪崩)。

    雪崩:一个服务失败,导致整条链路的服务都失败的情形。

  • Hystrix 主要功能:

    • 隔离
      • 线程池隔离(导入依赖,自动会进行线程池隔离)
      • 信号量隔离(每个服务只允许固定的访问数)
    • 降级(提供方和消费方都需要添加降级方案)
    • 熔断
    • 限流

Hystrix 降级

  • Hystrix 降级:当服务发生异常或调用超时,返回默认数据

服务提供方

步骤
  1. 在服务提供方,引入hystrix依赖

    <!-- hystrix -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>
    
  2. 定义降级方法

  3. 使用@HystrixCommand注解配置降级方法

  4. 在启动类上开启Hystrox功能:@EnableCircuitBreaker

pom.xml(依赖)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>hystrix-parent</artifactId>
        <groupId>com.itheima</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>hystrix-provider</artifactId>
    <dependencies>

        <!--spring boot web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

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

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

    </dependencies>

</project>
GoodsController.java(包含降级方法)
package com.itheima.provider.controller;

import com.itheima.provider.domain.Goods;
import com.itheima.provider.service.GoodsService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Goods Controller 服务提供方
 */

@RestController
@RequestMapping("/goods")
public class GoodsController {
    
    

    @Autowired
    private GoodsService goodsService;

    @Value("${server.port}")
    private int port;

    /**
     * 降级:
     * 1. 出现异常
     * 2. 服务调用超时
     *      - 默认1s超时
     *
     * 注解: @HystrixCommand(fallbackMethod = "findOne_fallback")
     *          fallbackMethod: 指定降级后调用的方法名称
     *
     */

    @GetMapping("/findOne/{id}")
    @HystrixCommand(fallbackMethod = "findOne_fallback", commandProperties = {
    
    
                    //将Hystrix的超时时间设置为3s,默认为1s
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    public Goods findOne(@PathVariable("id") int id) {
    
    

        Goods goods = goodsService.findOne(id);

        //自定义异常,如果id == 1,出现异常,不等于1,则正常,用来测试降级
        //if (id == 1) {
    
    
        //    int i = 1 / 0;
        //}

        //自定义超时,休眠2s,用来测试降级,然后注解中设置超时时间为3s,休眠2s也不再降级
        try {
    
    
            Thread.sleep(2000);
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }

        goods.setTitle(goods.getTitle() + ":" + port);//将端口号,设置到了 商品标题上
        return goods;
    }

    /**
     * 定义降级方法:
     *      方法的返回值、参数需要和原方法一样
     */
    public Goods findOne_fallback(int id) {
    
    
        Goods goods = new Goods();
        goods.setTitle("降级了...:" + e.getMessage());
        return goods;
    }
}
启动类(@EnableCircuitBreaker)
package com.itheima.provider;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@EnableEurekaClient //该注解 在新版本中可以省略
@SpringBootApplication
@EnableCircuitBreaker   //开启Hystrix功能
public class ProviderApp {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(ProviderApp.class,args);
    }
}
application.yml
server:
  port: 8000

eureka:
  instance:
    hostname: localhost # 主机名
    prefer-ip-address: true # 将当前实例的ip注册到eureka server 中。默认是false 注册主机名
    ip-address: 127.0.0.1 # 设置当前实例的ip
    instance-id: ${
    
    eureka.instance.ip-address}:${
    
    spring.application.name}:${
    
    server.port} # 设置web控制台显示的 实例id
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka
spring:
  application:
    name: hystrix-provider # 设置当前应用的名称。将来会在eureka中Application显示。将来需要使用该名称来获取路径

服务消费方

步骤
  1. feign 组件已经集成了 hystrix 组件

    <!--feign-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
    
  2. 定义feign调用接口实现类,重写方法,这个重写的方法就是降级方法

  3. 在@FeignClient注解中使用fallback属性设置降级处理类

  4. yml配置中开启feign.hystrix.enable = true

    # 开启feign对hystrix的支持
    feign:
      hystrix:
        enabled: true
    
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>hystrix-parent</artifactId>
        <groupId>com.itheima</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>hystrix-consumer</artifactId>

    <dependencies>

        <!--spring boot web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>


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

        <!--feign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

    </dependencies>
</project>
OrderController.java(不变)
package com.itheima.consumer.controller;


import com.itheima.consumer.domain.Goods;
import com.itheima.consumer.feign.GoodsFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/order")
public class OrderController {
    
    

    @Autowired
    private GoodsFeignClient goodsFeignClient;

    @GetMapping("/goods/{id}")
    public Goods findGoodsById(@PathVariable("id") int id){
    
    
        return goodsFeignClient.findGoodsById(id);
    }

}
feign调用接口(配置@FeignClient中fallback参数)
package com.itheima.consumer.feign;


import com.itheima.consumer.domain.Goods;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(value = "HYSTRIX-PROVIDER", fallback = GoodsFeignClientFallback.class)
public interface GoodsFeignClient {
    
    

    @GetMapping("/goods/findOne/{id}")
    Goods findGoodsById(@PathVariable("id") int id);

}
feign调用接口实现类
package com.itheima.consumer.feign;

import com.itheima.consumer.domain.Goods;
import org.springframework.stereotype.Component;

/**
 * Feign 客户端的降级处理类
 *  1.定义类,实现Feign客户端几口
 *  2.使用@Compnent注解将Bean加入SpringIOC容器
 */
@Component
public class GoodsFeignClientFallback implements GoodsFeignClient {
    
    
    @Override
    public Goods findGoodsById(int id) {
    
    
        Goods goods = new Goods();
        goods.setTitle("又被降级了...");
        return goods;
    }
}
application.yml(feign:hystrix:enable = true)
server:
  port: 9000

eureka:
  instance:
    hostname: localhost # 主机名
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka
spring:
  application:
    name: hystrix-consumer # 设置当前应用的名称。将来会在eureka中Application显示。将来需要使用该名称来获取路径

# 开启feign对hystrix的支持
feign:
  hystrix:
    enabled: true

Hystrix 异常处理

异常传播

只需要通过设置 @HystrixCommand 注解的 ignoreExceptions 参数,即可忽略指定异常类型功能,从而不触发服务降级。

@HystrixCommand(ignoreExceptions = {
    
    BusinessException.class})
public String helloService() {
    
    
    long start = System.currentTimeMillis();
    String body = restTemplate.getForEntity("http://SPRINGBOOT-EUREKA-CLIENT-OLD/hello", String.class).getBody();
    System.out.println("Spend time : " + (System.currentTimeMillis() - start));
    return body;
}

如上面方法的定义,当 helloService 方法抛出了类型为 BusinessException 的异常时,Hystrix 会将它包装在 HystrixBadRequestException 中抛出,浙江就不会触发后粗的 fallback 逻辑。

异常获取

Hystrix 命令因为异常(除了 HystrixBadRequestException 的异常)进入服务降级逻辑之后,往往需要对不同异常做针对性处理。

在使用注解配置方式的时候,实现异常的获取非常简单,只需要在 fallback 实现方法的参数中增加 Throwable e 的定义,这样在方法内部就可以获取触发服务降级的具体异常内容了,比如:

@HystrixCommand(fallbackMethod = "helloFallback", commandKey = "helloKey")
public String helloService() {
    
    
    long start = System.currentTimeMillis();
    String body = restTemplate.getForEntity("http://SPRINGBOOT-EUREKA-CLIENT-OLD/hello", String.class).getBody();
    System.out.println("Spend time : " + (System.currentTimeMillis() - start));
    return body;
}

public String helloFallback(Throwable e) {
    
    
    e.printStackTrace();
    return "服务降级,errorMsg:\r" + printStackTraceToString(e);
}

/**
 * 打印堆栈信息到字符串
 */
private String printStackTraceToString(Throwable e) {
    
    
    StringWriter sw = new StringWriter();
    e.printStackTrace(new PrintWriter(sw));
    return sw.getBuffer().toString();
}

Hystrix 命令名称、分组及线程池划分

Hystrix 使用命令分组将一起的命令进行管理,比如报告、警报、仪表盘或组/库。默认情况下,Hystrix使用 HystrixCommandGroupKey 来定义命令线程池,除非单独定义线程池。

线程池主要体现是用于监测、指标发布、缓存和其他此类用途的 HystrixThreadPool。 一个 HystrixCommand 与一个单独注入到它的 HystrixThreadPoolKey 所检索到的 HystrixThreadPool 相关联, 或者默认为使用 HystrixCommandGroupKey 的创建一个 。

当我们使用@HystrixCommand注解的时候,只需设置 @HystrixCommand 注解的 commandKeygroupKeythreadPoolKey 属性即可,他们分别表示了命令名称、分组以及线程池划分,比如我们可以像下面这样进行设置:

@HystrixCommand(commandKey = "helloService", groupKey = "helloGroup", threadPoolKey = "helloServiceThread")
public String helloService() {
    
    
    long start = System.currentTimeMillis();
    String body = restTemplate.getForEntity("http://SPRINGBOOT-EUREKA-CLIENT-OLD/hello", String.class).getBody();
    System.out.println("Spend time : " + (System.currentTimeMillis() - start));
    return body;
}

Hystrix 熔断(自动)

  • Hystrix 熔断机制,用于监控微服务调用情况,当失败的情况达到预定的阀值(默认5秒失败20次),会打开短裤器,拒绝所有请求,直到服务恢复正常为止。

熔断器的状态机制

  • Closed:熔断器关闭状态,调用失败次数积累,到了阈值(或一定比例)则启动熔断机制;
  • Open:熔断器打开状态,此时对下游的调用都内部直接返回错误,不走网络,但设计了一个时钟选项,默认的时钟达到了一定时间(这个时间一般设置成平均故障处理时间,也就是MTTR),到了这个时间,进入半熔断状态;
  • Half-Open:半熔断状态,允许定量的服务请求,如果调用都成功(或一定比例)则认为恢复了,关闭熔断器,否则认为还没好,又回到熔断器打开状态;

测试步骤

  1. 服务提供方Controller设置自定义异常

    //如果id == 1,出现异常,不等于1,则正常
    if (id == 1) {
          
          
        //自定义异常
        int i = 1 / 0;
    }
    
  2. 测试一:

    • URL中id=1(异常),访问时会降级;
    • URL中id=2(无异常),访问时不会降级;
  3. 测试二:

    • URL中id=1(异常),连续疯狂多次访问(20+);
    • URL中id=2(无异常),访问时会降级,说明熔断器为打开状态;

自定义熔断阈值

  • 监控的时间(默认5s):circuitBreaker.sleepWindowInMilliseconds
  • 失败次数(默认20次):circuitBreaker.requestVolumeThreshold
  • 失败率(默认50%):circuitBreaker.errorThresholdPercentage
package com.itheima.provider.controller;

import com.itheima.provider.domain.Goods;
import com.itheima.provider.service.GoodsService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Goods Controller 服务提供方
 */

@RestController
@RequestMapping("/goods")
public class GoodsController {
    
    

    @Autowired
    private GoodsService goodsService;

    @Value("${server.port}")
    private int port;

    /**
     * 降级:
     * 1. 出现异常
     * 2. 服务调用超时
     *      - 默认1s超时
     *
     * 注解: @HystrixCommand(fallbackMethod = "findOne_fallback")
     *          fallbackMethod: 指定降级后调用的方法名称
     *
     */

    @GetMapping("/findOne/{id}")
    @HystrixCommand(fallbackMethod = "findOne_fallback", commandProperties = {
    
    
                    //设置Hystrix的超时时间,默认为1s
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000"),
                    //监控的时间,默认5s(5000毫秒)
                    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "5000"),
                    //失败此时,默认20次
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "20"),
                    //失败率,默认50%
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50")
    })
    public Goods findOne(@PathVariable("id") int id) {
    
    

        Goods goods = goodsService.findOne(id);

        //如果id == 1,出现异常,不等于1,则正常
        if (id == 1) {
    
    
            //自定义异常
            int i = 1 / 0;
        }

        goods.setTitle(goods.getTitle() + ":" + port);//将端口号,设置到了 商品标题上
        return goods;
    }

    /**
     * 定义降级方法:
     *      方法的返回值、参数需要和原方法一样
     */
    public Goods findOne_fallback(int id) {
    
    
        Goods goods = new Goods();
        goods.setTitle("降级了...");
        return goods;
    }
}

Hystrix 仪表盘(Dashboard)

Spring cloud 除了对 Hystrix 的整合,还完美地整合了它的仪表盘组件 Hystrix Dashboard,它主要用来实时监控 Hystrix 的各项指标信息。通过 Hystrix Dashboard 反馈的实时信息,可以帮助我们快速发现系统中存在的问题,从而及时地才去应对措施。

Spring Cloud 中构建一个 Hystrix Dashboard 非常简单,只需要4步(具体依赖需根据实际项目依赖版本):

  1. 创建一个标准的 Spring Boot 工程,命名为 hystrix-dashboard

  2. 编辑pom.xml,具体依赖内容如下所示:

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>
    
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
    </dependency>
    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    
  3. 为应用主类加上 @EnableHystrixDashboard ,启动 Hystrix Dashboard 功能。

  4. 根据实际情况修改 application.properties 配置文件,比如选择一个未被占用的端口等,此步不是必需的。

    server.port=8089
    

经过四步操作,已经完成了基本配置,截下来可以启动应用,并访问 http://localhost:8089/hystrix。

从页面的文字内容中我们可以知道,Hystrix Dashboard 共支持三种不同的监控方式,如下所示:

  • 默认的集群监控:通过 URL https://turbine-hostname:port/turbine.stream 开启,实现对默认集群的监控。
  • 指定的集群监控:通过 URL https://turbine-hostname:port/turbine.stream?cluster=[clusterName]?cluster=[clusterName] 开启,实现对 clusterName 集群的监控。
  • 单体应用的监控:通过 URL https://hystrix-app:port/actuator/hystrix.stream 开启,实现对具体某个服务实例的监控。

前两者都是对集群的监控,需要整合 Turbine 才能实现。现在先来实现单个服务实例的监控。

单体应用监控

Hystrix Dashboard监控单实例节点需要通过访问实例的 /actuator/hystrix.stream 接口来实现,首先需要Wie服务实例添加这个端点,只需要下面几部:

  • 在服务实例 pom.xml 中的 dependencies 节点中增加 spring-boot-starter-actuator 监控模块已开启监控相关的端点,并确保已经引入断路器的依赖 spring-cloud-starter-hystrix

    <dependencies>
        
        ...
    
    	<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
    
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        
        ...
        
    </dependencies>
    
  • 确保在服务实例的主类中已经使用 @EnableCircuitBreaker 注解,开启了断路器功能。

  • 服务实例中增加配置暴露servlet /actuator/hystrix.stream

    @Bean
    public ServletRegistrationBean getServlet() {
          
          
    	HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
    	ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
    	registrationBean.setLoadOnStartup(1);
    	registrationBean.addUrlMappings("/actuator/hystrix.stream");
    	registrationBean.setName("HystrixMetricsStreamServlet");
    	return registrationBean;
    }
    
  • 通过dashboard控制台访问应用地址 http://localhost:8080/actuator/hystrix.stream,即可。

UNABLE TO CONNECT TO COMMAND METRIC STREAM 问题解决

dashboard的配置中改权限了,在dashboard的application配置文件中加入如下配置:

hystrix.dashboard.proxy-stream-allow-list=localhost
hystrix:
 dashboard:
     proxy-stream-allow-list:"localhost"

或者

hystrix.dashboard.proxy-stream-allow-list=*
hystrix:
 dashboard:
     proxy-stream-allow-list:"*"

Hystrix 熔断监控(Turbine聚合监控)

  • Hystrix 提供了Hystrix-dashboard功能,用于实时监控微服务运行状态。
  • 但是Hystrix-dashboard只能监控一个微服务。
  • Netflix 还提供了 Turbine,进行聚合监控。

1. 搭建监控模块,引入依赖

使用Turbine聚合监控多个Hystrix dashboard功能

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>hystrix-parent</artifactId>
        <groupId>com.itheima</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>hystrix-monitor</artifactId>


    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

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


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2. yml文件中进行配置

spring:
  application.name: hystrix-monitor
server:
  port: 8769
turbine:
  combine-host-port: true
  # 配置需要被监控的服务名称列表
  app-config: hystrix-provider,hystrix-consumer
  cluster-name-expression: "'default'"
  aggregator:
    cluster-config: default
  #instanceUrlSuffix: /actuator/hystrix.stream
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

3. 创建启动类

  • 注解开启 Turbine 聚合监控功能
    • @EnableTurbine
  • 注解开启 Hystrix仪表盘功能
    • @EnableHystrixDashboard
package com.itheima;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.cloud.netflix.turbine.EnableTurbine;

@SpringBootApplication
@EnableEurekaClient

@EnableTurbine //开启Turbine 很聚合监控功能
@EnableHystrixDashboard //开启Hystrix仪表盘监控功能
public class HystrixMonitorApp {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(HystrixMonitorApp.class, args);
    }

}

4. 被监控模块导入依赖

<!--turbine 监控-->

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

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

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

5. 被监控模块中添加Bean(高版本需要)

被监控模块的配置类中添加(启动类也可以)

@Bean
public ServletRegistrationBean getServlet() {
    
    
	HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
	ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
	registrationBean.setLoadOnStartup(1);
	registrationBean.addUrlMappings("/actuator/hystrix.stream");
	registrationBean.setName("HystrixMetricsStreamServlet");
	return registrationBean;
}

6. 被监控模块的启动类上添加注解

@EnableHystrixDashboard	// 开启Hystrix仪表盘监控功能

7. 启动测试

启动服务:

  • eureka-server
  • hystrix-provider
  • hystrix-consumer
  • hystrix-monitor

访问:

  • 在浏览器访问http://localhost:8769/hystrix/进入Hystrix Dashboard界面

  • 界面中输入监控的Url地址:http://localhost:8769/turbine.stream,监控时间间隔2000毫秒和title

界面解释:

  • 实心圆:它有颜色和大小之分,分别代表实例的监控程度和流量大小。
  • 曲线:用来记录 2 分钟内流量的相对变化,我们可以通过它来观察到流量的上升和下降趋势。

猜你喜欢

转载自blog.csdn.net/weixin_52610802/article/details/128267422