Spring Cloud は Hystrix ヒューズを統合します

ハイストリックスヒューズ

ハイストリックスの概要

  • Hystrix は、Netflix がオープンソース化した遅延およびフォールトトレランス ライブラリであり、リモート サービスやサードパーティ ライブラリへのアクセスを分離して、カスケード障害 (雪崩) を防ぐために使用されます。

    雪崩: 1 つのサービスに障害が発生し、リンク全体のサービスに障害が発生する状況。

  • 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);
    }
}
アプリケーション.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. インターフェイス実装クラスを呼び出してメソッドをオーバーライドするように定義します。このオーバーライドされたメソッドがダウングレード メソッドです。

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

}
偽の呼び出しインターフェイス (@FeignClient構成内のフォールバック パラメーター)
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);

}
偽装呼び出しインターフェイス実装クラス
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スローし、Zhejiang は後続のロジックをトリガーしません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コマンド グループを使用して、レポート、アラート、ダッシュボード、グループ/ライブラリなどのコマンドをまとめて管理します。HystrixCommandGroupKeyデフォルトでは、スレッド プールが個別に定義されていない限り、Hystrix はコマンド スレッド プールの定義に使用します。

スレッド プールは主に、監視、指標の公開、キャッシュなどの目的で使用されますHystrixThreadPoolは、HystrixCommand個別に挿入されるHystrixThreadPoolKey取得されたものにHystrixThreadPool関連付けられるか、HystrixCommandGroupKeyを使用してデフォルトで作成されます。

@HystrixCommand@HystrixCommand アノテーションを使用する場合、アノテーションのcommandKeygroupKey、および属性を設定するだけで済みますthreadPoolKey。これらはそれぞれコマンド名、グループ化、スレッド プールの分割を表します。たとえば、次のように設定できます。

@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 回失敗します)、サーバーはオンになり、サービスが通常に戻るまですべてのリクエストは拒否されます。

ヒューズのステータスメカニズム

  • 閉:ヒューズ閉状態、失敗した通話の数が蓄積され、それがしきい値 (または特定の割合) に達すると、サーキット ブレーカー メカニズムがアクティブになります。
  • オープン:ヒューズオープン状態, 現時点では、すべてのダウンストリーム呼び出しはネットワークを経由せずに内部で直接エラーを返しますが、クロック オプションが設計されており、デフォルトのクロックは特定の時間に達します (この時間は通常、平均障害処理時間に設定されます)。 MTTR) この時間に達すると、半ヒューズ状態に入ります。
  • ハーフオープン:半ブロー状態, 一定量のサービス要求を許可します。呼び出しが成功した場合 (または一定の割合)、回復したとみなされ、ヒューズが閉じられます。そうでない場合は、回復していないとみなされ、ヒューズが開いた状態に戻ります。 ;

テスト手順

  1. サービスプロバイダーコントローラーがカスタム例外を設定する

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

    • URL の id=1 (異常) にアクセスするとダウングレードされます。
    • URL の id=2 は (例外なく) アクセス中にダウングレードされません。
  3. テスト 2:

    • URL の id=1 (異常)、連続して何度もアクセスされました (20 回以上)。
    • URL の id=2 (例外なし) はアクセス中にダウングレードされ、ヒューズが開いていることを示します。

カスタマイズされたサーキットブレーカーのしきい値

  • 監視時間 (デフォルトは 5 秒):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;
    }
}

ハイストリックスダッシュボード

Spring cloudHystrixの統合に加えて、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
    

4 つのステップを経て基本的な設定が完了したので、スクリーンショットを撮った後、アプリケーションを起動して http://localhost:8089/hystrix にアクセスできるようになります。

ページのテキスト内容から、Hystrix Dashboard次の 3 つの異なる監視方法がサポートされていることがわかります。

  • デフォルトのクラスター監視: https://turbine-hostname:port/turbine.streamURL から開き、デフォルトのクラスターを監視します。
  • 指定されたクラスター監視: https://turbine-hostname:port/turbine.stream?cluster=[clusterName]?cluster=[clusterName]URL から開き、clusterNameクラスターを監視します。
  • 単一アプリケーションの監視: https://hystrix-app:port/actuator/hystrix.streamURL を通じて開き、特定のサービス インスタンスを監視します。

最初の 2 つはクラスター監視であり、Turbineそれらを実現するには統合する必要があります。次に、単一のサービス インスタンスの監視を実装しましょう。

単一アプリケーションの監視

Hystrix ダッシュボードは、インスタンスのインターフェイスにアクセスして単一インスタンス ノードを監視します/actuator/hystrix.stream。まず、このエンドポイントを Wie サービス インスタンスに追加する必要があります。必要な手順は次のとおりです:

  • サービス インスタンス pom.xml の依存関係ノードに監視モジュールを追加して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サーキット ブレーカー機能を有効にするために、サービス インスタンスのメイン クラスでアノテーションが使用されていることを確認してください。

  • サービス インスタンスでサーブレットを公開するための構成を追加する/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;
    }
    
  • ダッシュボード コンソールからアプリケーション アドレスにアクセスするだけですhttp://localhost:8080/actuator/hystrix.stream

コマンド・メトリック・ストリームに接続できない問題の解決

ダッシュボード構成の権限が変更されました。次の構成をダッシュ​​ボード アプリケーション構成ファイルに追加します。

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 ヒューズ監視 (タービン集約監視)

  • Hystrix は、マイクロサービスの実行状況をリアルタイムに監視するための Hystrix-dashboard 機能を提供します。
  • ただし、Hystrix ダッシュボードは 1 つのマイクロサービスのみを監視できます。
  • Netflix は、集約モニタリング用の Turbine も提供しています。

1. 監視モジュールを構築し、依存関係を導入する

Turbine アグリゲーションを使用して複数の Hystrix ダッシュボード機能を監視する

<?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. スタートアップクラスの作成

  • 注釈を付けてタービン集約監視機能を有効にする
    • @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. テストを開始する

サービスを開始します。

  • エウレカサーバー
  • ヒストリックスプロバイダー
  • ヒストリックス消費者
  • ヒストリックスモニター

アクセス:

  • ブラウザでhttp://localhost:8769/hystrix/Hystrix ダッシュボード インターフェイスにアクセスします。

  • インターフェイスに監視 URL アドレスを入力します: http://localhost:8769/turbine.stream、監視時間間隔 2000 ミリ秒、タイトル

インターフェースの説明:

  • 黒丸:色と大きさでインスタンスの監視度、トラフィック量をそれぞれ表します。
  • 曲線: 2 分以内のトラフィックの相対的な変化を記録するために使用され、トラフィックの上昇傾向と下降傾向を観察するために使用できます。

おすすめ

転載: blog.csdn.net/weixin_52610802/article/details/128267422