[봄 - 클라우드 - 알리바바] 센티넬 지속성 규칙

, 운동에 앞서 한 응용 프로그램의 다시 시작, 당신은해야 할 우리의 실제 프로젝트가없는 실용적인 것을, 다음 아래 규칙 우리의 구성을 저장 할 수있는 방법은 없습니다, 그래서 다시 구성해야합니까? 대답은 YES, 그 다음 어떻게 지속 센티넬 규칙을 소개하는 방법을 알려주는 것이다.

문서 : 포털

  • 파일 데이터 소스 (파일 저장)
    • 풀 모드
    • 푸시 모드
  • Nacos 구성
  • 아폴로
파일 데이터 소스
풀 모드

원리 :
확장 쓰기 데이터 소스 ( WritableDataSource) 정기적으로 규칙 관리 센터, 클라이언트 적극적으로 폴링 당겨 규칙은이 규칙 등 RDBMS, 파일의 중심이 될 수있다
풀 모드 데이터 소스 (예 등 로컬 파일, RDBMS로) 일반적으로 사용할 수있는 작성. 클라이언트는 등록 된 데이터 소스를 사용할 필요가 : 레지스터 데이터가 등록 소스의 전송에 데이터를 기록, 해당 소스 RuleManager에 해당하는 읽기 WritableDataSourceRegistry에.

다음 프로세스는 다음과 같습니다

데모를 당겨
  • 1 단계 : 프로필 추가

        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-extension</artifactId>
        </dependency>
  • 2 단계 : 그 구현 지속성 코드를 작성com.alibaba.csp.sentinel.init.InitFunc

    • 코드에서 참조 : 포털
    import com.alibaba.csp.sentinel.command.handler.ModifyParamFlowRulesCommandHandler;
    import com.alibaba.csp.sentinel.datasource.*;
    import com.alibaba.csp.sentinel.init.InitFunc;
    import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
    import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
    import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
    import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
    import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
    import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
    import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
    import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
    import com.alibaba.csp.sentinel.slots.system.SystemRule;
    import com.alibaba.csp.sentinel.slots.system.SystemRuleManager;
    import com.alibaba.csp.sentinel.transport.util.WritableDataSourceRegistry;
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.TypeReference;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.List;
    
    /**
     * FileDataSourceInit for : 自定义Sentinel存储文件数据源加载类
     *
     * @author <a href="mailto:[email protected]">Isaac.Zhang | 若初</a>
     * @since 2019/7/21
     */
    public class FileDataSourceInit implements InitFunc {
        @Override
        public void init() throws Exception {
            // TIPS: 如果你对这个路径不喜欢,可修改为你喜欢的路径
            String ruleDir = System.getProperty("user.home") + "/sentinel/rules";
            String flowRulePath = ruleDir + "/flow-rule.json";
            String degradeRulePath = ruleDir + "/degrade-rule.json";
            String systemRulePath = ruleDir + "/system-rule.json";
            String authorityRulePath = ruleDir + "/authority-rule.json";
            String hotParamFlowRulePath = ruleDir + "/param-flow-rule.json";
    
            this.mkdirIfNotExits(ruleDir);
            this.createFileIfNotExits(flowRulePath);
            this.createFileIfNotExits(degradeRulePath);
            this.createFileIfNotExits(systemRulePath);
            this.createFileIfNotExits(authorityRulePath);
            this.createFileIfNotExits(hotParamFlowRulePath);
            // 流控规则
            ReadableDataSource<String, List<FlowRule>> flowRuleRDS = new FileRefreshableDataSource<>(
                    flowRulePath,
                    flowRuleListParser
            );
            // 将可读数据源注册至FlowRuleManager
            // 这样当规则文件发生变化时,就会更新规则到内存
            FlowRuleManager.register2Property(flowRuleRDS.getProperty());
            WritableDataSource<List<FlowRule>> flowRuleWDS = new FileWritableDataSource<>(
                    flowRulePath,
                    this::encodeJson
            );
            // 将可写数据源注册至transport模块的WritableDataSourceRegistry中
            // 这样收到控制台推送的规则时,Sentinel会先更新到内存,然后将规则写入到文件中
            WritableDataSourceRegistry.registerFlowDataSource(flowRuleWDS);
    
            // 降级规则
            ReadableDataSource<String, List<DegradeRule>> degradeRuleRDS = new FileRefreshableDataSource<>(
                    degradeRulePath,
                    degradeRuleListParser
            );
            DegradeRuleManager.register2Property(degradeRuleRDS.getProperty());
            WritableDataSource<List<DegradeRule>> degradeRuleWDS = new FileWritableDataSource<>(
                    degradeRulePath,
                    this::encodeJson
            );
            WritableDataSourceRegistry.registerDegradeDataSource(degradeRuleWDS);
    
            // 系统规则
            ReadableDataSource<String, List<SystemRule>> systemRuleRDS = new FileRefreshableDataSource<>(
                    systemRulePath,
                    systemRuleListParser
            );
            SystemRuleManager.register2Property(systemRuleRDS.getProperty());
            WritableDataSource<List<SystemRule>> systemRuleWDS = new FileWritableDataSource<>(
                    systemRulePath,
                    this::encodeJson
            );
            WritableDataSourceRegistry.registerSystemDataSource(systemRuleWDS);
    
            // 授权规则
            ReadableDataSource<String, List<AuthorityRule>> authorityRuleRDS = new FileRefreshableDataSource<>(
                    flowRulePath,
                    authorityRuleListParser
            );
            AuthorityRuleManager.register2Property(authorityRuleRDS.getProperty());
            WritableDataSource<List<AuthorityRule>> authorityRuleWDS = new FileWritableDataSource<>(
                    authorityRulePath,
                    this::encodeJson
            );
            WritableDataSourceRegistry.registerAuthorityDataSource(authorityRuleWDS);
    
            // 热点参数规则
            ReadableDataSource<String, List<ParamFlowRule>> hotParamFlowRuleRDS = new FileRefreshableDataSource<>(
                    hotParamFlowRulePath,
                    hotParamFlowRuleListParser
            );
            ParamFlowRuleManager.register2Property(hotParamFlowRuleRDS.getProperty());
            WritableDataSource<List<ParamFlowRule>> paramFlowRuleWDS = new FileWritableDataSource<>(
                    hotParamFlowRulePath,
                    this::encodeJson
            );
            ModifyParamFlowRulesCommandHandler.setWritableDataSource(paramFlowRuleWDS);
        }
    
        /**
         * 流控规则对象转换
         */
        private Converter<String, List<FlowRule>> flowRuleListParser = source -> JSON.parseObject(
                source,
                new TypeReference<List<FlowRule>>() {
                }
        );
        /**
         * 降级规则对象转换
         */
        private Converter<String, List<DegradeRule>> degradeRuleListParser = source -> JSON.parseObject(
                source,
                new TypeReference<List<DegradeRule>>() {
                }
        );
        /**
         * 系统规则对象转换
         */
        private Converter<String, List<SystemRule>> systemRuleListParser = source -> JSON.parseObject(
                source,
                new TypeReference<List<SystemRule>>() {
                }
        );
    
        /**
         * 授权规则对象转换
         */
        private Converter<String, List<AuthorityRule>> authorityRuleListParser = source -> JSON.parseObject(
                source,
                new TypeReference<List<AuthorityRule>>() {
                }
        );
    
        /**
         * 热点规则对象转换
         */
        private Converter<String, List<ParamFlowRule>> hotParamFlowRuleListParser = source -> JSON.parseObject(
                source,
                new TypeReference<List<ParamFlowRule>>() {
                }
        );
    
        /**
         * 创建目录
         *
         * @param filePath
         */
        private void mkdirIfNotExits(String filePath) {
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
        }
    
        /**
         * 创建文件
         *
         * @param filePath
         * @throws IOException
         */
        private void createFileIfNotExits(String filePath) throws IOException {
            File file = new File(filePath);
            if (!file.exists()) {
                file.createNewFile();
            }
        }
    
        private <T> String encodeJson(T t) {
            return JSON.toJSONString(t);
        }
    }
  • 3 단계 : 위의 코드를 사용

    자원 디렉토리 생성 resources/META-INF/services디렉토리 및 파일을 작성 com.alibaba.csp.sentinel.init.InitFunc읽고 :

    com.sxzhongf.sharedcenter.configuration.sentinel.datasource.FileDataSourceInit
장점과 단점을 당겨
  • 이점
    1. 어떤 의존하지 않고, 간단한
    2. 외부 종속성이 없습니다
  • 결점
    1. 일관성을 보장하지 않습니다 (규칙을 사용하는 것입니다 FileRefreshableDataSource업데이트, 지연이있을 것이다)
    2. 실시간을 보장하지 않습니다 (규칙을 사용하는 것은되어 FileRefreshableDataSource정기적으로 업데이트)
    3. 또한 성능 문제가있을 수 있습니다 너무 자주 당겨
    4. 파일이 로컬에 저장되어 있기 때문에, 쉽게 손실
  • 참고 :
    1. ITMUCH
    2. 센티넬 WIKI
푸시 모드

권장 콘솔이 일정한 규칙의 중심에 푸시 될 것이다 규칙을 설정하여 클라이언트 구현 ReadableDataSource인터페이스 끝 센터 실시간 액세스 규칙의 변경 사항을 모니터링 , 다음과 같은 과정은 다음과 같습니다

  • 원리

    1. Nacos / 원격 구성 센터 콘솔 푸시 규칙
    2. 센티넬 클라이언트 선박 Nacos 구성 변경은 로컬 캐시를 업데이트
  • shared_center 서비스 처리

    1. 따라 추가
      <dependency>
          <groupId>com.alibaba.csp</groupId>
          <artifactId>sentinel-datasource-nacos</artifactId>
      </dependency>
    1. 구성 추가
    spring:
      cloud:
        sentinel:
          datasource:
            sxzhongf_flow:
              nacos:
                server-addr: localhost:8848
                dataId: ${spring.application.name}-flow-rules
                groupId: SENTINEL_GROUP
                # 规则类型,取值见:org.springframework.cloud.alibaba.sentinel.datasource.RuleType
                rule_type: flow
            sxzhongf_degrade:
              nacos:
                server-addr: localhost:8848
                dataId: ${spring.application.name}-degrade-rules
                groupId: SENTINEL_GROUP
                rule-type: degrade
  • 센티넬 대시 보드 처리

    대시 변환은 두 개의 인터페이스를 통해 주로 규칙 :

    com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvidercom.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher

    • 다운로드 센티넬 소스 코드를

    • 원래 수정 sentinel-dashboard프로젝트의 POM 파일을

          <!-- for Nacos rule publisher sample -->
          <dependency>
              <groupId>com.alibaba.csp</groupId>
              <artifactId>sentinel-datasource-nacos</artifactId>
              <!--注释掉原文件中的scope,让其不仅在test的时候生效-->
              <!--<scope>test</scope>-->
          </dependency>
    • 게으른 모드 : 복사 sentinel-dashboard(테스트 대상 항목 아래 nacos 패키지를

      src/test/java/com/alibaba/csp/sentinel/dashboard/rule/nacos하려면 src/main/java/com/alibaba/csp/sentinel/dashboard/rule다음

    • 기본 컨트롤러 공급 업체 및 게시자 수정

      com.alibaba.csp.sentinel.dashboard.controller.v2.FlowControllerV2

          @Autowired
          // @Qualifier("flowRuleDefaultProvider")
              @Qualifier("flowRuleNacosProvider")
          private DynamicRuleProvider<List<FlowRuleEntity>> ruleProvider;
          @Autowired
              // @Qualifier("flowRuleDefaultPublisher")
          @Qualifier("flowRuleNacosPublisher")
          private DynamicRulePublisher<List<FlowRuleEntity>> rulePublisher;
    • 오픈 /Sentinel-1.6.2/sentinel-dashboard/src/main/webapp/resources/app/scripts/directives/sidebar/sidebar.html코드를 수정, 파일 :

      <!--<li ui-sref-active="active">-->
                  <!--<a ui-sref="dashboard.flow({app: entry.app})">-->
                    <!--<i class="glyphicon glyphicon-filter"></i>&nbsp;&nbsp;流控规则 V1</a>-->
      <!--</li>-->
      
      ---
      
      改为
      
        <li ui-sref-active="active">
          <a ui-sref="dashboard.flow({app: entry.app})">
            <i class="glyphicon glyphicon-filter"></i>&nbsp;&nbsp;NACOS 流控规则 V1</a>
        </li>

    코드를 수정하려는 대시 보드는 잘하고있다.

  • 센티넬 - 대시 보드를 다시 시작 mvn clean package -DskipTests

  • 테스트 결과

    센티넬 추가 흐름 제어 규칙 :

    Nacos 동기화 구성을 볼 수 :


추천

출처www.cnblogs.com/zhangpan1244/p/11228020.html