天天看點

Sentinel Dashboard(基于1.8.1)流控規則持久化到Nacos——涉及部分Sentinel Dashboard源碼改造

前言

  之前雖然也一直在使用sentinel實作限流熔斷功能,但卻沒有好好整理之前看的源碼與資料,今天有時間将之前自己整理過的資料寫成一篇博文,或者是是一篇關于Sentinel(基于目前最近版本1.8,如果沒有特殊說明,都指最新1.8版本)持久化Nacos的指南,因為我發現網上的一些博文雖然有參考價值但卻沒有好好完善好細節,一知半解,或者版本比較老不具備參考價值。比如說為什麼要做這一步,這一步需要完成什麼具體工作等等。是以盡我所能,詳細介紹下手把手整合Sentinel與Nacos,實作Sentinel Dashboard控制台到Nacos配置中心的流控規則通信并下發規則到具體應用。

  前提是要對Sentinel Dashboard跟Nacos有一定的了解,具體可以檢視官方wiki,參考資料也是來源于此,再加上對sentinel-dashboard源碼參考改造。

博文中源碼已上傳至github(https://github.com/Jian0110/learning-cloudalibaba),歡迎小夥伴們star...

一、準備工作

1、Sentinel Dashboard持久化

  我們首先需要知道:在Sentinel Dashboard中配置規則之後重新開機應用就會丢失,是以實際生産環境中需要配置規則的持久化實作,Sentinel提供多種不同的資料源來持久化規則配置,包括file,redis、nacos、zk。

  這就需要涉及到Sentinel Dashboard的規則管理及推送功能:集中管理和推送規則。

sentinel-core

 提供 API 和擴充接口來接收資訊。開發者需要根據自己的環境,選取一個可靠的推送規則方式;同時,規則最好在控制台中集中管理。

  而規則管理推送主要有以下三種模式:

      

Sentinel Dashboard(基于1.8.1)流控規則持久化到Nacos——涉及部分Sentinel Dashboard源碼改造

                (以上部分文字跟截圖來源自官方wiki)

  很明顯,我們需要的是第三種Push模式,即Sentinel Dashboard統一管理配置(有良好的UI界面,為什麼不能統一管理呢,明顯比Nacos編寫json要專業),然後将規則統一推送到Nacos并持久化(生成配置檔案),最後用戶端監聽Nacos(這一部了解使用過Nacos的話應該很熟,采用ConfigService.getConfg()方法擷取配置檔案),下發配置生成Rule。如下圖(虛線部分不推薦):

        

Sentinel Dashboard(基于1.8.1)流控規則持久化到Nacos——涉及部分Sentinel Dashboard源碼改造

  換句話說就是實作Sentinel Dashboard與Nacos之間的互相通信:

  • Sentinel Dashboard界面配置流控規則---釋出/推送--->Nacos生成配置檔案并持久化;
  • 通過Nacos配置檔案修改流控規則---拉取--->Sentinel Dashboard界面顯示最新的流控規則。

  需要注意的是:

  • 在Nacos控制台上修改流控制,雖然可以同步到Sentinel Dashboard,但是Nacos此時應該作為一個流控規則的持久化平台,是以正常操作過程應該是開發者在Sentinel Dashboard上修改流控規則後同步到Nacos,遺憾的是目前Sentinel Dashboard不支援該功能。
  • 試想下,如果公司沒有統一在Sentinel Dashboard或Nacos中二選一進行配置,而是一會在Sentinel Dashboard配置,一會在Nacos配置。那麼就會出現很嚴重的問題(流控規則達不到預期,配置資料不一緻),是以推薦使用Sentinel Dashboard統一界面進行配置管理流控規則

正因為Sentinel Dashboard目前版本(截至目前為止是1.8.1-SNAPSHOT)暫不支援,但是可以通過改造部分源碼實作此功能,具體請看下面介紹。

2、Sentinel Dashboard流控規則源碼改造須知

首先通過git拉取下載下傳源碼,導入idea工程,解析maven後觀察sentinel-dashboard子產品目錄結構

git clone https://github.com/alibaba/Sentinel.git      

github可能會很慢,如果隻是研究源碼了解的話,有需要源碼打包的話,可以評論或私信發給你壓縮包。

改造前,我們所要了解實作Sentinel Dashboard與Nacos互相通信需要經曆哪些流程或者說是缺少哪些流程,我們才好對症下藥,根據我的了解我歸納總結出一下幾點

(1)流控規則Controller入口

  Sentinel Dashboard的流控規則下的所有操作,都會調用Sentinel-Dashboard源碼中的FlowControllerV1類,這個類中包含流控規則本地化的CRUD操作;

                

Sentinel Dashboard(基于1.8.1)流控規則持久化到Nacos——涉及部分Sentinel Dashboard源碼改造

 在com.alibaba.csp.sentinel.dashboard.controller.v2包下存在一個FlowControllerV2;類,這個類同樣提供流控規則的CURD,與V1不同的是,它可以實作指定資料源的規則拉取和釋出。

Sentinel Dashboard(基于1.8.1)流控規則持久化到Nacos——涉及部分Sentinel Dashboard源碼改造

  官方說明:

  從 Sentinel 1.4.0 開始,我們抽取出了接口用于向遠端配置中心推送規則以及拉取規則:

  • DynamicRuleProvider<T>

    : 拉取規則
  • DynamicRulePublisher<T>

    : 推送規則
  以 Nacos 為例,若希望使用 Nacos 作為動态規則配置中心,使用者可以提取出相關的類,然後隻需在 

FlowControllerV2

 中指定對應的 bean 即可開啟 Nacos 适配
@Autowired
@Qualifier("flowRuleNacosProvider")
private DynamicRuleProvider<List<FlowRuleEntity>> ruleProvider;
@Autowired
@Qualifier("flowRuleNacosPublisher")
private DynamicRulePublisher<List<FlowRuleEntity>> rulePublisher;      

是以根據官網說明,我們知道,FlowControllerV2依賴兩個非常重要的類

  • DynamicRuleProvider:動态規則的拉取,從指定資料源中擷取控制後在Sentinel Dashboard中展示。
  • DynamicRulePublisher:動态規則釋出,将在Sentinel Dashboard中修改的規則同步到指定資料源中。

隻需要擴充這兩個類,然後內建Nacos來實作Sentinel Dashboard規則同步。

(2)Sentinel Dashboard前端sidebar.html頁面入口

在目錄resources/app/scripts/directives/sidebar找到sidebar.html,裡面有關于V1版本的請求入口:

<li ui-sref-active="active" ng-if="!entry.isGateway">
    <a ui-sref="dashboard.flowV1({app: entry.app})">
      <i class="glyphicon glyphicon-filter"></i>&nbsp;&nbsp;流控規則</a>
</li>      

 對應的JS請求如下,可以看到請求就是V1版本的Controller,那麼之後的改造需要重新對應V2版本的Controller

.state('dashboard.flowV1', {
        templateUrl: 'app/views/flow_v1.html',
        url: '/flow/:app',
        controller: 'FlowControllerV1',
        resolve: {
          loadMyFiles: ['$ocLazyLoad', function ($ocLazyLoad) {
            return $ocLazyLoad.load({
              name: 'sentinelDashboardApp',
              files: [
                'app/scripts/controllers/flow_v1.js',
              ]
            });
          }]
        }
      })      

(3)Sentinel Dashboard缺少Nacos配置

在源碼中雖然官方提供了test示例(即test目錄)下關于Nacos等持久化示例,但是具體的實作還需要一些細節,比如在Sentinel Dashboard配置Nacos的serverAddr、namespace、groupId,并且通過Nacos擷取配置檔案擷取服務清單等。

Sentinel Dashboard(基于1.8.1)流控規則持久化到Nacos——涉及部分Sentinel Dashboard源碼改造

例如:NacosConfig中ConfigFactory.createConfigService("localhost")并沒有實作建立具體的nacos config service,而是預設localhost

@Configuration
public class NacosConfig {

    @Bean
    public Converter<List<FlowRuleEntity>, String> flowRuleEntityEncoder() {
        return JSON::toJSONString;
    }

    @Bean
    public Converter<String, List<FlowRuleEntity>> flowRuleEntityDecoder() {
        return s -> JSON.parseArray(s, FlowRuleEntity.class);
    }

    @Bean
    public ConfigService nacosConfigService() throws Exception {
        return ConfigFactory.createConfigService("localhost");
    }
}      

application.properties檔案中也沒有Nacos的相關配置

#spring settings
spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true

#cookie name setting
server.servlet.session.cookie.name=sentinel_dashboard_cookie

#logging settings
logging.level.org.springframework.web=INFO
logging.file=C:\\Users\\Administrator/logs/csp/sentinel-dashboard.log
logging.pattern.file= %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
#logging.pattern.console= %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n

#auth settings
auth.filter.exclude-urls=/,/auth/login,/auth/logout,/registry/machine,/version
auth.filter.exclude-url-suffixes=htm,html,js,css,map,ico,ttf,woff,png
# If auth.enabled=false, Sentinel console disable login
auth.username=sentinel
auth.password=sentinel

# Inject the dashboard version. It's required to enable
# filtering in pom.xml for this resource file.
sentinel.dashboard.version=1.8.1-SNAPSHOT      

(4)流控規則配置檔案限制

在NacosConfigutils已經指定了預設的流控規則配置檔案的groupId等,但是如果需要指定的話這裡也需要修改

public final class NacosConfigUtil {


    /**
     * 流控規則配置檔案預設在SENTINEL_GROUP組、DATA_ID以-flow-rules結尾
     */
    public static final String FLOW_DATA_ID_POSTFIX = "-flow-rules";
    public static final String GROUP_ID = "SENTINEL_GROUP";
    // 省略

}      

這樣我們在Sentinel用戶端就可以這麼配置指定流控規則配置檔案限制了

spring.cloud.sentinel.datasource.flow.nacos.server-addr=127.0.0.1:8848
spring.cloud.sentinel.datasource.flow.nacos.data-id=${spring.application.name}-flow-rules
spring.cloud.sentinel.datasource.flow.nacos.group-id=SENTINEL_GROUP
spring.cloud.sentinel.datasource.flow.nacos.data-type=json
spring.cloud.sentinel.datasource.flow.nacos.rule-type=flow      

二、改造Sentinel Dashboard源碼實作Nacos持久化

有了以上的須知以及改造前準備工作之後,我們可以開始進行改造源碼,其中需要修改部分都會做相關注釋

1、在pom.xml檔案中去掉test scope注釋

這是因為官方提供的Nacos持久化用例都是在test目錄下,是以scope需要去除test,需要sentinel-datasource-nacos包的支援。之後将修改好的源碼放在源碼主目錄下,而不是繼續在test目錄下。

<!-- for Nacos rule publisher sample -->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-nacos</artifactId>
            <!--<scope>test</scope>-->
        </dependency>      

2、修改前端路由配置(sidebar.html)

找到resources/app/scripts/directives/sidebar/sidebar.html檔案修改,修改flowV1為flow,去掉V1,這樣的話會調用FlowControllerV2接口

<!--<li ui-sref-active="active" ng-if="!entry.isGateway">
            <a ui-sref="dashboard.flowV1({app: entry.app})">
              <i class="glyphicon glyphicon-filter"></i>&nbsp;&nbsp;流控規則</a>
          </li>-->
          <!-- 修改為flow,直接調用FlowControllerV2 -->
          <li ui-sref-active="active" ng-if="!entry.isGateway">
            <a ui-sref="dashboard.flow({app: entry.app})">
              <i class="glyphicon glyphicon-filter"></i>&nbsp;&nbsp;流控規則</a>
          </li>      

這樣就可以通過js跳轉至FlowControllerV2了

.state('dashboard.flow', {
          templateUrl: 'app/views/flow_v2.html',
          url: '/v2/flow/:app',
          controller: 'FlowControllerV2',
          resolve: {
              loadMyFiles: ['$ocLazyLoad', function ($ocLazyLoad) {
                  return $ocLazyLoad.load({
                      name: 'sentinelDashboardApp',
                      files: [
                          'app/scripts/controllers/flow_v2.js',
                      ]
                  });
              }]
          }
      })      

3、建立nacos配置

(1)流控配置檔案限制

我們采用官方的限制,即 預設 Nacos 适配的 dataId 和 groupId 約定如下:

  • groupId: SENTINEL_GROUP
  • 流控規則 dataId: {appName}-flow-rules,比如應用名為 appA,則 dataId 為 appA-flow-rules

是以不需要修改NacosConfigUtil.java了,但這是展示是為了步驟的完整性。

(2)建立讀取nacos配置的NacosPropertiesConfiguration檔案并且application.properties指定配置

package com.alibaba.csp.sentinel.dashboard.rule.nacos;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "sentinel.nacos")
public class NacosPropertiesConfiguration {
    private String serverAddr;
    private String dataId;
    private String groupId = "SENTINEL_GROUP"; // 預設分組
    private String namespace;
   // 省略 getter/setter  
}      

然後配置sentinel-dashboar/resources/application.properties中配置nacos配置,以為sentinel.nacos為字首:

# nacos config server
sentinel.nacos.serverAddr=127.0.0.1:8848
sentinel.nacos.namespace=
sentinel.nacos.group-id=SENTINEL-GROUP      

(3)改造NacosConfig,建立NacosConfigService

@EnableConfigurationProperties(NacosPropertiesConfiguration.class)
@Configuration
public class NacosConfig {

    @Bean
    public Converter<List<FlowRuleEntity>, String> flowRuleEntityEncoder() {
        return JSON::toJSONString;
    }

    @Bean
    public Converter<String, List<FlowRuleEntity>> flowRuleEntityDecoder() {
        return s -> JSON.parseArray(s, FlowRuleEntity.class);
    }

    @Bean
    public ConfigService nacosConfigService(NacosPropertiesConfiguration nacosPropertiesConfiguration) throws Exception {
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, nacosPropertiesConfiguration.getServerAddr());
        properties.put(PropertyKeyConst.NAMESPACE, nacosPropertiesConfiguration.getNamespace());
        return ConfigFactory.createConfigService(properties);
//        return ConfigFactory.createConfigService("localhost");
    }
}      

NacosConfig主要做兩件事:

1) 注入Convert轉換器,将FlowRuleEntity轉化成FlowRule,以及反向轉化

2) 注入Nacos配置服務ConfigService

4、動态實作從Nacos配置中心擷取流控規則——重寫FlowRuleNacosProvider與FlowRuleNacosPublisher類

重寫FlowRuleNacosProvider類

@Service("flowRuleNacosProvider")
public class FlowRuleNacosProvider implements DynamicRuleProvider<List<FlowRuleEntity>> {
    public static final Logger log = LoggerFactory.getLogger(FlowRuleNacosProvider.class);

    @Autowired
    private ConfigService configService;
    @Autowired
    private Converter<String, List<FlowRuleEntity>> converter;


    /**
     * 1)通過ConfigService的getConfig()方法從Nacos Config Server讀取指定配置資訊
     * 2)通過轉為converter轉化為FlowRule規則
     * @param appName
     * @return
     * @throws Exception
     */
    @Override
    public List<FlowRuleEntity> getRules(String appName) throws Exception {
        String rules = configService.getConfig(appName + NacosConfigUtil.FLOW_DATA_ID_POSTFIX,
            NacosConfigUtil.GROUP_ID, 3000);
        log.info("obtain flow rules from nacos config:{}", rules);
        if (StringUtil.isEmpty(rules)) {
            return new ArrayList<>();
        }
        return converter.convert(rules);
    }
}      

重寫FlowRuleNacosPublisher類:

@Service("flowRuleNacosPublisher")
public class FlowRuleNacosPublisher implements DynamicRulePublisher<List<FlowRuleEntity>> {
    public static final Logger log = LoggerFactory.getLogger(FlowRuleNacosPublisher.class);
    @Autowired
    private ConfigService configService;
    @Autowired
    private Converter<List<FlowRuleEntity>, String> converter;


    /**
     * 通過configService的publishConfig()方法将rules釋出到nacos
     * @param app app name
     * @param rules list of rules to push
     * @throws Exception
     */
    @Override
    public void publish(String app, List<FlowRuleEntity> rules) throws Exception {
        AssertUtil.notEmpty(app, "app name cannot be empty");
        if (rules == null) {
            return;
        }
        log.info("sentinel dashboard push rules: {}", rules);
        configService.publishConfig(app + NacosConfigUtil.FLOW_DATA_ID_POSTFIX,
            NacosConfigUtil.GROUP_ID, converter.convert(rules));
    }
}      

5、複制到源碼主目錄下

  之後需要将上述檔案(com.alibaba.csp.sentinel.dashboard.test.rule.nacos)複制到com.alibaba.csp.sentinel.dashboard.rule.nacos目錄下,即去掉test目錄,這樣是以内源碼中Nacos等持久化的配置都是在test中,打包jar的時候并不會打包進去,是以需要copy到主源碼目錄下。

              

Sentinel Dashboard(基于1.8.1)流控規則持久化到Nacos——涉及部分Sentinel Dashboard源碼改造

6、修改FlowControllerV2類,使用@Qulifier将上面配置的兩個類注入進來

@RestController
@RequestMapping(value = "/v2/flow")
public class FlowControllerV2 {

    private final Logger logger = LoggerFactory.getLogger(FlowControllerV2.class);

    @Autowired
    private InMemoryRuleRepositoryAdapter<FlowRuleEntity> repository;

    /*@Autowired
    @Qualifier("flowRuleDefaultProvider")
    private DynamicRuleProvider<List<FlowRuleEntity>> ruleProvider;
    @Autowired
    @Qualifier("flowRuleDefaultPublisher")
    private DynamicRulePublisher<List<FlowRuleEntity>> rulePublisher;*/
    /**
     * 修改預設publisher/provider為Nacos
     * 使用@Qualifier指定bean
     */
    @Autowired
    @Qualifier("flowRuleNacosProvider")
    private DynamicRuleProvider<List<FlowRuleEntity>> ruleProvider;
    @Autowired
    @Qualifier("flowRuleNacosPublisher")
    private DynamicRulePublisher<List<FlowRuleEntity>> rulePublisher;

    // 省略      
}      

7、mvn clean package打包

先install sentinel-parent保證依賴包已經install到本地repository

之後打包sentinel-dashboard子產品,執行mvn clean package指令,打包成jar包

Sentinel Dashboard(基于1.8.1)流控規則持久化到Nacos——涉及部分Sentinel Dashboard源碼改造

如果以上步驟嫌麻煩,或者中間過程哪裡有問題,可以私信我直接要jar包。

三、流控規則持久化測試

1、編寫Sentinel用戶端

(1)建立springboot應用,編寫pom檔案如下:

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <sentinel.version>1.8.1-SNAPSHOT</sentinel.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--  sentinel核心庫 -->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-core</artifactId>
            <version>${sentinel.version}</version>
        </dependency>
        <!-- 通過nacos持久化流控規則 -->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-nacos</artifactId>
            <version>${sentinel.version}</version>
        </dependency>
        <!--  sentinel AspectJ 的擴充用于自動定義資源 -->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-annotation-aspectj</artifactId>
            <version>${sentinel.version}</version>
        </dependency>
        <!-- sentinel 整合spring cloud alibaba -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
            <version>2.1.2.RELEASE</version>
        </dependency>

        <!-- sentinel用戶端與dashboard通信依賴 -->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-transport-simple-http</artifactId>
            <version>${sentinel.version}</version>
        </dependency>
    </dependencies>      

(2)配置nacos,配置sentinel dashboard datasource資訊:

  1)bootstrap.properties中配置Nacos Config Server

spring.cloud.nacos.config.server-addr=127.0.0.1:8848      

  2)application.properties配置sentinel dashboard datasource

server.port=6003
spring.application.name=sentinel
management.endpoints.web.exposure.include=*
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
spring.cloud.sentinel.transport.dashboard=127.0.0.1:6005
#指定csp.sentinel.api.port時需要配置,否則預設8719
#spring.cloud.sentinel.transport.port=6007

# sentinel nacos配置
spring.cloud.sentinel.datasource.flow.nacos.server-addr=127.0.0.1:8848
spring.cloud.sentinel.datasource.flow.nacos.data-id=${spring.application.name}-flow-rules
spring.cloud.sentinel.datasource.flow.nacos.group-id=SENTINEL_GROUP
spring.cloud.sentinel.datasource.flow.nacos.data-type=json
spring.cloud.sentinel.datasource.flow.nacos.rule-type=flow      

(3)編寫SayHelloController,指定/hello資源節點

package com.cloud.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SayHelloController {

    @RequestMapping("/hello")
    public String sayHello(){
        return "hello Jian";
    }
}      

2、啟動Nacos

我使用的是win10下啟動nacos,之後登入Nacos

檢視起初是沒有${spring.application.name}-flow-rules配置檔案,也沒有SENTINEL-GROUP分組;

Sentinel Dashboard(基于1.8.1)流控規則持久化到Nacos——涉及部分Sentinel Dashboard源碼改造

但是服務清單會sentinel用戶端執行個體:

Sentinel Dashboard(基于1.8.1)流控規則持久化到Nacos——涉及部分Sentinel Dashboard源碼改造

配置設定的虛拟IP與port

Sentinel Dashboard(基于1.8.1)流控規則持久化到Nacos——涉及部分Sentinel Dashboard源碼改造

3、啟動sentinel dashboard控制台

(1)啟動sentinel dashboard

 找到target/sentinel-dashboard.jar,執行指令:

java -Dserver.port=6005 -Dcsp.sentinel.dashboard.server=localhost:6006 -Dproject.name=sentinel-dashboard -Dcsp.sentinel.api.port=6007 -jar target/sentinel-dashboard.jar      

具體的啟動參數介紹:

  -Dserver.port=6005 控制台端口,sentinel控制台是一個spring boot程式。用戶端配置檔案需要填對應的配置,如:spring.cloud.sentinel.transport.dashboard=192.168.1.102:8718

  -Dcsp.sentinel.dashboard.server=localhost:6007 控制台的位址,指定控制台後用戶端會自動向該位址發送心跳包。

  -Dproject.name=sentinel-dashboard  指定Sentinel控制台程式的名稱

  -Dcsp.sentinel.api.port=8719 可選項,用戶端提供給Dashboard通路或者檢視Sentinel的運作通路的參數,預設8719

其它啟動配置項,具體檢視官方wiki

(2)登入sentinel dashboard配置流控規則

 1)輸入localhost:6005通路sentinel dashboard控制台(登入使用者/密碼預設sentinel)

 2)選擇sentinel菜單-流控規則-新增流控規則-輸入配置-新增

  

Sentinel Dashboard(基于1.8.1)流控規則持久化到Nacos——涉及部分Sentinel Dashboard源碼改造

   如圖所示,我們選擇QPS門檻值類型,并且count為2,流控模式為預設的直接模式,流控效果快速失敗(這些配置具體含義參看官網wiki)  

注意:一開始可能會空白頁面,這可能是由于機器時間機制導緻的,此時可能還未發送心跳,加之sentinel控制台預設的又是懶加載模式(可去除該設定),是以最好是我們通路sentinel用戶端的/hello接口然後重新整理頁面,即通路:http://192.168.1.156:6003/hello(ip:port是由Nacos配置設定的虛拟位址)

4、通路/hello接口

不停重新整理通路/hello接口,觀察sentinel dashboard界面中的實時監控。看到有通過QPS與拒絕QPS的實時監控情況,說明該sentinel用戶端已成功接入sentinel dashboard。

Sentinel Dashboard(基于1.8.1)流控規則持久化到Nacos——涉及部分Sentinel Dashboard源碼改造

5、測試Sentinel Dashboard流控規則到Nacos的持久化

(1)确認Sentinel Dashboard是否能正确釋出流控規則到Nacos

  在Sentinel Dashboard針對sentinel用戶端的/hello資源節點已經配置了流控規則

Sentinel Dashboard(基于1.8.1)流控規則持久化到Nacos——涉及部分Sentinel Dashboard源碼改造

  此時Nacos會對此次流控規則生成持久化配置檔案,切換到Nacos-配置清單檢視确實存在分組SENTINEL_GROUP下的sentinel-flow-rules配置檔案

Sentinel Dashboard(基于1.8.1)流控規則持久化到Nacos——涉及部分Sentinel Dashboard源碼改造

  點選檢視具體内容,發現關鍵資訊都是正确的,說明Sentinel Dashboard釋出到Nacos通信已經打通

Sentinel Dashboard(基于1.8.1)流控規則持久化到Nacos——涉及部分Sentinel Dashboard源碼改造

(2)确認Sentinel Dashboard從nacos拉取流控規則配置是否成功

  修改分組SENTINEL_GROUP下的sentinel-flow-rules配置檔案,修改count(QPS數)為5,然後點選釋出

Sentinel Dashboard(基于1.8.1)流控規則持久化到Nacos——涉及部分Sentinel Dashboard源碼改造

  釋出後切換到Sentinel Dashboard檢視/hello資源點的流控規則的門檻值是否發生變化

Sentinel Dashboard(基于1.8.1)流控規則持久化到Nacos——涉及部分Sentinel Dashboard源碼改造

  明顯已經發生變化,因為Sentinel Dashboard是懶加載模式,是以重新整理後背景才有日志輸出:

2020-12-15 19:40:11.499  INFO 11196 --- [nio-6005-exec-8] c.a.c.s.d.r.nacos.FlowRuleNacosProvider  : obtain flow rules from nacos config:[{"app":"sentinel","clusterConfig":{"acquireRef
useStrategy":0,"clientOfflineTime":2000,"fallbackToLocalWhenFail":true,"resourceTimeout":2000,"resourceTimeoutStrategy":0,"sampleCount":10,"strategy":0,"thresholdType":0,"windowInterva
lMs":1000},"clusterMode":false,"controlBehavior":0,"count":2.0,"gmtCreate":1608026073444,"gmtModified":1608026073444,"grade":1,"id":2,"ip":"169.254.102.85","limitApp":"default","port":
8720,"resource":"/hello","strategy":0}]
2020-12-15 19:51:22.612  INFO 11196 --- [nio-6005-exec-9] c.a.c.s.d.r.nacos.FlowRuleNacosProvider  : obtain flow rules from nacos config:[{"app":"sentinel","clusterConfig":{"acquireRef
useStrategy":0,"clientOfflineTime":2000,"fallbackToLocalWhenFail":true,"resourceTimeout":2000,"resourceTimeoutStrategy":0,"sampleCount":10,"strategy":0,"thresholdType":0,"windowInterva
lMs":1000},"clusterMode":false,"controlBehavior":0,"count":5.0,"gmtCreate":1608026073444,"gmtModified":1608026073444,"grade":1,"id":2,"ip":"169.254.102.85","limitApp":"default","port":
8720,"resource":"/hello","strategy":0}]      

  這說明Sentinel Dashboard能從nacos成功拉取流控規則配置

 (3)驗證流控規則是否生效

  此時我們的QPS門檻值為5,也就是說1s之間内我們需要超過通路5次,則會被sentinel限流。不斷通路/hello資源節點,觀察傳回

Sentinel Dashboard(基于1.8.1)流控規則持久化到Nacos——涉及部分Sentinel Dashboard源碼改造

  傳回Blocked By Sentinel(flow limiting)說明限流規則已經生效。此時實時監控上也會出現通過的QPS數目為5

Sentinel Dashboard(基于1.8.1)流控規則持久化到Nacos——涉及部分Sentinel Dashboard源碼改造

繼續閱讀