Spring Cloud integra el fusible Hystrix

Fusible Hystrix

Descripción general de Hystrix

  • Hystrix es una biblioteca de código abierto de Netflix con tolerancia a retrasos y fallas que se utiliza para aislar el acceso a servicios remotos y bibliotecas de terceros para evitar fallas en cascada (avalanchas).

    Avalancha : situación en la que falla un servicio, lo que provoca que fallen los servicios a lo largo de todo el enlace.

  • Funciones principales de Hystrix:

    • aislamiento
      • Aislamiento del grupo de subprocesos (importe dependencias, el aislamiento del grupo de subprocesos se realizará automáticamente)
      • Aislamiento de semáforo (solo se permite un número fijo de accesos por servicio)
    • Bajar de categoría (tanto los proveedores como los consumidores deben agregar planes de bajada de categoría)
    • fusible
    • Limitando

Rebaja de Hystrix

  • Degradación de Hystrix: cuando se produce una excepción en el servicio o se agota el tiempo de espera de la llamada, se devuelven los datos predeterminados

proveedor de servicio

paso
  1. Del lado del proveedor de servicios, introducir hystrixdependencias.

    <!-- hystrix -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>
    
  2. Definir método de degradación

  3. @HystrixCommandConfigurar métodos de degradación mediante anotaciones

  4. Habilite la función Hystrox en la clase de inicio:@EnableCircuitBreaker

pom.xml (dependencia)
<?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 (contiene métodos de degradación)
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;
    }
}
Clase de inicio (@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);
    }
}
aplicación.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显示。将来需要使用该名称来获取路径

consumidor de servicios

paso
  1. El componente fingido ha integrado el componente hystrix.

    <!--feign-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
    
  2. Defina fingir llamar a la clase de implementación de la interfaz y anular el método. Este método anulado es el método de degradación.

  3. Utilice el atributo de reserva en la anotación @FeignClient para configurar la clase de procesamiento de degradación

  4. Habilitar en la configuración de ymlfeign.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 (sin cambios)
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);
    }

}
fingir interfaz de llamada ( @FeignClientparámetro alternativo en la configuración)
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);

}
fingir llamadas clase de implementación de interfaz
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 (fingir: hystrix: habilitar = verdadero)
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

Manejo de excepciones de Hystrix

Propagación de anomalías

Con solo configurar los parámetros @HystrixCommandde la anotación ignoreExceptions, puede ignorar la función de tipo de excepción especificada, sin provocar así la degradación del servicio.

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

Como se define en el método anterior, cuando helloServiceel método arroja BusinessExceptionuna excepción de tipo, Hystrix la envolverá y HystrixBadRequestExceptionla lanzará, y Zhejiang no activará la fallbacklógica posterior.

Adquisición de excepción

Cuando Hystrixel comando ingresa a la lógica de degradación del servicio debido a excepciones (excepto HystrixBadRequestExceptionlas excepciones), a menudo es necesario manejar diferentes excepciones de manera específica.

Cuando se utiliza el método de configuración de anotaciones, es muy sencillo obtener excepciones. Solo necesita agregar fallbackla definición de en los parámetros del método de implementación Throwable e, para que pueda obtener el contenido de excepción específico que desencadena la degradación del servicio dentro del método, como :

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

Nombre del comando Hystrix, agrupación y división del grupo de subprocesos

HystrixUtilice grupos de comandos para administrar comandos juntos, como informes, alertas, paneles o grupos/bibliotecas. De forma predeterminada, Hystrix utiliza HystrixCommandGroupKeypara definir el grupo de subprocesos de comando a menos que el grupo de subprocesos se defina por separado.

El grupo de subprocesos se utiliza principalmente para monitoreo, publicación de indicadores, almacenamiento en caché y otros fines similares HystrixThreadPool. A se asocia con un recuperado que se HystrixCommandinyecta en él individualmente , o se crea uno por defecto usando .HystrixThreadPoolKeyHystrixThreadPoolHystrixCommandGroupKey

Cuando usamos la anotación @HystrixCommand, solo necesitamos configurar los atributos , y @HystrixCommandde la anotación . Representan el nombre del comando, la agrupación y la división del grupo de subprocesos respectivamente. Por ejemplo, podemos configurarlo de la siguiente manera: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;
}

Fusible Hystrix (automático)

  • El mecanismo de disyuntor de Hystrix se utiliza para monitorear las llamadas de microservicio. Cuando la falla alcanza un umbral predeterminado (El valor predeterminado es 5 segundos y falla 20 veces.), el servidor se encenderá y todas las solicitudes serán rechazadas hasta que el servicio vuelva a la normalidad.

El mecanismo de estado del fusible.

  • Cerrado: estado cerrado del fusible, el número de llamadas fallidas se acumula y cuando alcanza un umbral (o una determinada proporción), se activa el mecanismo disyuntor;
  • Abierto: estado de fusible abiertoEn este momento, todas las llamadas descendentes devolverán errores directamente internamente, sin pasar por la red, pero se diseña una opción de reloj. El reloj predeterminado alcanza un tiempo determinado (este tiempo generalmente se establece en el tiempo medio de procesamiento de fallas, es decir, MTTR) Cuando se alcance este tiempo, ingrese al estado semi-fusible;
  • Medio abierto: estado medio abierto, permitiendo una cierta cantidad de solicitudes de servicio, si las llamadas son exitosas (o una cierta proporción) se considerará recuperada y el fusible se cerrará, en caso contrario se considerará no recuperada y volverá al estado de fusible abierto. ;

Pasos de prueba

  1. El controlador del proveedor de servicios establece excepciones personalizadas

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

    • El id=1 en la URL (anormal) se degradará cuando se acceda;
    • El id=2 en la URL (sin excepción) no se degradará durante el acceso;
  3. Prueba 2:

    • El id=1 en la URL (anormal), visitado muchas veces seguidas (20+);
    • El id = 2 en la URL (sin excepción) se degradará durante el acceso, lo que indica que el fusible está abierto;

Umbral de disyuntor personalizado

  • Tiempo de monitoreo (5s predeterminado):circuitBreaker.sleepWindowInMilliseconds
  • Número de fallas (por defecto 20):circuitBreaker.requestVolumeThreshold
  • Tasa de fracaso (predeterminado 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;
    }
}

Panel de control Hystrix

Spring cloudAdemás de Hystrixla integración de , también integra perfectamente su componente de tablero Hystrix Dashboard, que se utiliza principalmente para monitorear Hystrixdiversa información de indicadores en tiempo real. La información en tiempo real retroalimentada Hystrix Dashboardpuede ayudarnos a descubrir rápidamente problemas en el sistema, para que podamos tomar contramedidas de manera oportuna.

Spring CloudCrear uno es Hystrix Dashboardmuy simple y solo requiere 4 pasos (las dependencias específicas deben basarse en la versión de dependencia real del proyecto):

  1. Cree un Spring Bootproyecto estándar llamado hystrix-dashboard.

  2. Edite pom.xml, el contenido de dependencia específico es el siguiente:

    <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. @EnableHystrixDashboardAgregue la función de inicio a la clase de aplicación principal Hystrix Dashboard.

  4. Modifique el archivo de configuración según la situación real application.properties, como seleccionar un puerto desocupado, etc. Este paso no es necesario.

    server.port=8089
    

Después de cuatro pasos, se completó la configuración básica, después de tomar la captura de pantalla, puede iniciar la aplicación y acceder a http://localhost:8089/hystrix.

Por el contenido del texto de la página, podemos saber que Hystrix Dashboardse admiten tres métodos de monitoreo diferentes, de la siguiente manera:

  • Monitoreo de clúster predeterminado: https://turbine-hostname:port/turbine.streamábralo a través de URL para monitorear el clúster predeterminado.
  • Monitoreo de clúster especificado: https://turbine-hostname:port/turbine.stream?cluster=[clusterName]?cluster=[clusterName]ábralo a través de URL para clusterNamemonitorear el clúster.
  • Monitoreo de aplicaciones individuales: https://hystrix-app:port/actuator/hystrix.streamábralo a través de URL para monitorear una instancia de servicio específica.

Los dos primeros son el seguimiento de grupos y deben integrarse Turbinepara lograrlos. Ahora implementemos el monitoreo de una única instancia de servicio.

Monitoreo de una sola aplicación

Hystrix Dashboard monitorea los nodos de instancia única accediendo a la /actuator/hystrix.streaminterfaz de la instancia. Primero, debe agregar este punto final a la instancia del servicio Wie. Solo necesita los siguientes pasos:

  • Agregue el módulo de monitoreo al nodo de dependencias en la instancia de servicio pom.xml spring-boot-starter-actuatorpara habilitar el monitoreo de puntos finales relacionados y garantizar que se hayan introducido las dependencias de los disyuntores 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>
    
  • Asegúrese de que la anotación se haya utilizado en la clase principal de la instancia de servicio @EnableCircuitBreakerpara habilitar la función de disyuntor.

  • Agregar configuración para exponer el servlet en la instancia de servicio/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;
    }
    
  • Simplemente acceda a la dirección de la aplicación a través de la consola del tablero http://localhost:8080/actuator/hystrix.stream.

NO SE PUEDE CONECTAR A COMMAND METRIC STREAM resolución de problemas

Los permisos se han cambiado en la configuración del panel. Agregue la siguiente configuración al archivo de configuración de la aplicación del panel:

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

o

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

Monitoreo de fusibles Hystrix (monitoreo de agregación de turbinas)

  • Hystrix proporciona la función Hystrix-dashboard para monitorear en tiempo real el estado de ejecución de los microservicios.
  • Pero Hystrix-dashboard solo puede monitorear un microservicio.
  • Netflix también ofrece Turbine para monitoreo agregado.

1. Cree un módulo de monitoreo e introduzca dependencias.

Supervise múltiples funciones del panel de Hystrix mediante la agregación de Turbine

<?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. Configurar en el archivo 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. Crear clase de inicio

  • Anotar para habilitar la función de monitoreo de agregación de turbinas
    • @EnableTurbine
  • La anotación habilita la función del panel de 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. El módulo monitoreado importa dependencias.

<!--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. Agregue beans al módulo monitoreado (requerido para versiones superiores)

Agréguelo a la clase de configuración del módulo monitoreado (también se puede usar la clase de inicio)

@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. Agregue anotaciones a la clase de inicio del módulo monitoreado.

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

7. Comience a probar

Iniciar el servicio:

  • servidor-eureka
  • proveedor-hystrix
  • consumidor-hystrix
  • monitor-hystrix

acceso:

  • http://localhost:8769/hystrix/Acceda a la interfaz de Hystrix Dashboard en el navegador

  • Ingrese la dirección URL de monitoreo en la interfaz: http://localhost:8769/turbine.stream, intervalo de tiempo de monitoreo 2000 milisegundos y título

Explicación de la interfaz:

  • Círculo sólido: Tiene colores y tamaños, que representan el grado de monitoreo y el volumen de tráfico de la instancia respectivamente.
  • Curva: se utiliza para registrar los cambios relativos en el tráfico en 2 minutos. Podemos usarlo para observar las tendencias ascendentes y descendentes del tráfico.

Supongo que te gusta

Origin blog.csdn.net/weixin_52610802/article/details/128267422
Recomendado
Clasificación