Spring Cloud integrates Hystrix fuse

Hystrix fuse

Hystrix Overview

  • Hystrix is ​​a delay and fault-tolerance library open sourced by Netflix. It is used to isolate access to remote services and third-party libraries to prevent cascading failures (avalanches).

    Avalanche : A situation in which one service fails, causing services along the entire link to fail.

  • Hystrix main functions:

    • isolation
      • Thread pool isolation (import dependencies, thread pool isolation will be automatically performed)
      • Semaphore isolation (only a fixed number of accesses allowed per service)
    • Downgrade (both providers and consumers need to add downgrade plans)
    • fuse
    • Limiting

Hystrix downgrade

  • Hystrix downgrade: When an exception occurs in the service or the call times out, default data is returned

service provider

step
  1. On the service provider side, introduce hystrixdependencies

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

  3. @HystrixCommandConfiguring downgrade methods using annotations

  4. Enable the Hystrox function on the startup class:@EnableCircuitBreaker

pom.xml (dependency)
<?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 (contains downgrade methods)
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;
    }
}
Startup class (@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显示。将来需要使用该名称来获取路径

service consumer

step
  1. The feign component has integrated the hystrix component

    <!--feign-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
    
  2. Define feign to call the interface implementation class and override the method. This overridden method is the downgrade method.

  3. Use the fallback attribute in the @FeignClient annotation to set the downgrade processing class

  4. Enable in yml configurationfeign.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 (unchanged)
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 calling interface ( @FeignClientfallback parameter in configuration)
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 calls interface implementation class
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 exception handling

Anomaly propagation

Just by setting the parameters @HystrixCommandof the annotation ignoreExceptions, you can ignore the specified exception type function, thereby not triggering service degradation.

@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;
}

As defined in the above method, when helloServicethe method throws BusinessExceptionan exception of type, Hystrix will wrap it in and HystrixBadRequestExceptionthrow it, and Zhejiang will not trigger the subsequent fallbacklogic.

Exception acquisition

When Hystrixthe command enters the service degradation logic due to exceptions (except HystrixBadRequestExceptionfor exceptions), different exceptions often need to be handled in a targeted manner.

When using the annotation configuration method, it is very simple to obtain exceptions. You only need to fallbackadd the definition of in the parameters of the implementation method Throwable e, so that you can obtain the specific exception content that triggers service degradation inside the method, such as:

@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 command name, grouping and thread pool division

HystrixUse command groups to manage commands together, such as reports, alerts, dashboards, or groups/libraries. By default, Hystrix uses HystrixCommandGroupKeyto define the command thread pool unless the thread pool is defined separately.

The thread pool is mainly used for monitoring, indicator publishing, caching and other such purposes HystrixThreadPool. A is associated with a retrieved that is HystrixCommandinjected into it individually , or one is created by default using .HystrixThreadPoolKeyHystrixThreadPoolHystrixCommandGroupKey

When we use the @HystrixCommand annotation, we only need to set the , , and attributes @HystrixCommandof the annotation . They represent the command name, grouping, and thread pool division respectively. For example, we can set it as follows: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 fuse (automatic)

  • Hystrix circuit breaker mechanism is used to monitor microservice calls. When the failure reaches a predetermined threshold (Default is 5 seconds and fails 20 times), the server will be turned on and all requests will be rejected until the service returns to normal.

The status mechanism of the fuse

  • Closed: fuse closed state, the number of failed calls accumulates, and when it reaches a threshold (or a certain proportion), the circuit breaker mechanism is activated;
  • Open: fuse open status, at this time, all downstream calls will directly return errors internally, without going through the network, but a clock option is designed. The default clock reaches a certain time (this time is generally set to the mean failure processing time, that is, MTTR). When this time is reached, , enter the semi-fuse state;
  • Half-Open: half blown state, allowing a certain amount of service requests. If the calls are successful (or a certain proportion), it will be considered recovered and the fuse will be closed. Otherwise, it will be considered not recovered and it will return to the fuse open state;

Test steps

  1. Service provider Controller sets custom exceptions

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

    • The id=1 in the URL (abnormal) will be downgraded when accessed;
    • The id=2 in the URL (no exception) will not be downgraded during access;
  3. Test 2:

    • The id=1 in the URL (abnormal), visited many times in a row (20+);
    • The id=2 in the URL (no exception) will be downgraded during access, indicating that the fuse is open;

Customized circuit breaker threshold

  • Monitoring time (default 5s):circuitBreaker.sleepWindowInMilliseconds
  • Number of failures (default 20):circuitBreaker.requestVolumeThreshold
  • Failure rate (default 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 cloudIn addition to Hystrixthe integration of , it also perfectly integrates its dashboard component Hystrix Dashboard, which is mainly used to monitor Hystrixvarious indicator information in real time. The real-time information fed Hystrix Dashboardback can help us quickly discover problems in the system, so that we can take countermeasures in a timely manner.

Spring CloudBuilding one in is Hystrix Dashboardvery simple and only requires 4 steps (specific dependencies need to be based on the actual project dependency version):

  1. Create a standard Spring Bootproject named hystrix-dashboard.

  2. Edit pom.xml, the specific dependency content is as follows:

    <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. @EnableHystrixDashboardAdd the startup function to the main application class Hystrix Dashboard.

  4. Modify the configuration file according to the actual situation application.properties, such as selecting an unoccupied port, etc. This step is not necessary.

    server.port=8089
    

After four steps, the basic configuration has been completed. After taking the screenshot, you can start the application and access http://localhost:8089/hystrix.

From the text content of the page, we can know that Hystrix Dashboardthree different monitoring methods are supported, as follows:

  • Default cluster monitoring: https://turbine-hostname:port/turbine.streamOpen through URL to monitor the default cluster.
  • Specified cluster monitoring: https://turbine-hostname:port/turbine.stream?cluster=[clusterName]?cluster=[clusterName]Open through URL to clusterNamemonitor the cluster.
  • Monitoring of single applications: https://hystrix-app:port/actuator/hystrix.streamOpen through URL to monitor a specific service instance.

The first two are cluster monitoring and need to be integrated Turbineto achieve them. Now let’s implement monitoring of a single service instance.

Single application monitoring

Hystrix Dashboard monitors single-instance nodes by accessing the instance's /actuator/hystrix.streaminterface. First, you need to add this endpoint to the Wie service instance. You only need the following steps:

  • Add the monitoring module to the dependencies node in the service instance pom.xml spring-boot-starter-actuatorto enable monitoring of related endpoints, and ensure that circuit breaker dependencies have been introduced 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>
    
  • Make sure that the annotation has been used in the main class of the service instance @EnableCircuitBreakerto enable the circuit breaker function.

  • Add configuration to expose servlet in service instance/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;
    }
    
  • Just access the application address through the dashboard console http://localhost:8080/actuator/hystrix.stream.

UNABLE TO CONNECT TO COMMAND METRIC STREAM problem solving

The permissions have been changed in the dashboard configuration. Add the following configuration to the dashboard application configuration file:

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

or

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

Hystrix fuse monitoring (Turbine aggregation monitoring)

  • Hystrix provides the Hystrix-dashboard function for real-time monitoring of the running status of microservices.
  • But Hystrix-dashboard can only monitor one microservice.
  • Netflix also offers Turbine for aggregate monitoring.

1. Build a monitoring module and introduce dependencies

Monitor multiple Hystrix dashboard functions using Turbine aggregation

<?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. Configure in yml file

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. Create startup class

  • Annotate to enable Turbine aggregation monitoring function
    • @EnableTurbine
  • Annotation enables Hystrix dashboard function
    • @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. The monitored module imports dependencies

<!--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. Add beans to the monitored module (required for higher versions)

Add it to the configuration class of the monitored module (the startup class can also be used)

@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. Add annotations to the startup class of the monitored module

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

7. Start testing

Start the service:

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

access:

  • http://localhost:8769/hystrix/Access the Hystrix Dashboard interface in the browser

  • Enter the monitoring Url address in the interface: http://localhost:8769/turbine.stream, monitoring time interval 2000 milliseconds and title

Interface explanation:

  • Solid circle: It has colors and sizes, which represent the monitoring degree and traffic volume of the instance respectively.
  • Curve: used to record the relative changes in traffic within 2 minutes. We can use it to observe the upward and downward trends of traffic.

Guess you like

Origin blog.csdn.net/weixin_52610802/article/details/128267422