Ver código fonte

sentinel 限流 熔断 实现nacos持久化
保存户型图接口

dengsixing 3 anos atrás
pai
commit
1f7ad34d20

+ 6 - 0
4dkankan-center-scene/pom.xml

@@ -68,6 +68,12 @@
             <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
         </dependency>
 
+        <dependency>
+            <groupId>com.alibaba.csp</groupId>
+            <artifactId>sentinel-datasource-nacos</artifactId>
+            <version>1.7.2</version>
+        </dependency>
+
 
     </dependencies>
 

+ 65 - 0
4dkankan-center-scene/src/main/java/com/fdkankan/scene/config/DataSourceInitFunc.java

@@ -0,0 +1,65 @@
+//package com.fdkankan.scene.config;
+//
+//import com.alibaba.cloud.sentinel.SentinelProperties;
+//import com.alibaba.cloud.sentinel.datasource.config.NacosDataSourceProperties;
+//import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
+//import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
+//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.fastjson.JSON;
+//import com.alibaba.fastjson.TypeReference;
+//import java.util.List;
+//import lombok.extern.slf4j.Slf4j;
+//import org.springframework.beans.factory.annotation.Autowired;
+//import org.springframework.context.annotation.Bean;
+//import org.springframework.context.annotation.Configuration;
+//
+///**
+// * <p>
+// * TODO
+// * </p>
+// *
+// * @author dengsixing
+// * @since 2022/2/14
+// **/
+//@Configuration
+//@Slf4j
+//public class DataSourceInitFunc {
+//
+//    @Autowired
+//    private SentinelProperties sentinelProperties;
+//
+//    @Bean
+//    public DataSourceInitFunc init() throws Exception {
+//
+//        log.info("[NacosSource初始化,从Nacos中获取熔断规则]");
+//
+//        sentinelProperties.getDatasource().entrySet().stream().filter(map -> {
+//            return map.getValue().getNacos() != null;
+//        }).forEach(map -> {
+//            NacosDataSourceProperties nacos = map.getValue().getNacos();
+//            // 限流规则,需要Nacos的dataId中包含flow字符串
+//            if (nacos.getDataId().contains("flow")) {
+//                ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new NacosDataSource<>(nacos.getServerAddr(),
+//                    nacos.getGroupId(), nacos.getDataId(),
+//                    source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
+//                    }));
+//                FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
+//            }
+//
+//            // 降级规则,需要Nacos的dataId中包含degrade字符串
+//            if (nacos.getDataId().contains("degrade")) {
+//                ReadableDataSource<String, List<DegradeRule>> degradeRuleDataSource = new NacosDataSource<>(nacos.getServerAddr(),
+//                    nacos.getGroupId(), nacos.getDataId(),
+//                    source -> JSON.parseObject(source, new TypeReference<List<DegradeRule>>() {
+//                    }));
+//                DegradeRuleManager.register2Property(degradeRuleDataSource.getProperty());
+//            }
+//
+//        });
+//        return new DataSourceInitFunc();
+//    }
+//
+//}

+ 15 - 1
4dkankan-center-scene/src/main/java/com/fdkankan/scene/controller/SceneEditController.java

@@ -349,7 +349,7 @@ public class SceneEditController extends BaseController {
      * @return com.fdkankan.common.response.ResultData
      **/
     @PostMapping(value = "/saveRoam")
-    public ResultData saveRoam(@RequestBody @Validated SaveRoamParamVO param) throws Exception {
+    public ResultData saveRoam(@RequestBody @Validated BaseDataParamVO param) throws Exception {
         return sceneProService.saveRoam(param);
     }
 
@@ -606,6 +606,20 @@ public class SceneEditController extends BaseController {
     }
 
     /**
+     * <p>
+     上传后保存
+     * </p>
+     * @author dengsixing
+     * @date 2022/1/20
+     * @param param
+     * @return com.fdkankan.common.response.ResultData
+     **/
+    @PostMapping(value = "/save/cad")
+    public ResultData saveUpload(@RequestBody @Validated BaseDataParamVO param) throws Exception{
+        return sceneEditInfoService.saveCad(param);
+    }
+
+    /**
      * 获取场景详情
      */
     @GetMapping(value = "/getInfo")

+ 2 - 3
4dkankan-center-scene/src/main/java/com/fdkankan/scene/controller/TestController.java

@@ -80,13 +80,12 @@ public class TestController {
 //        }
 //        try {
 
-//            String aaa = null;
-//            aaa.equals("123");
+            String aaa = null;
+            aaa.equals("123");
 
 //            String test = "123";
 //            if(test.equals("123")){
 //                throw new BusinessException(-1, "dsfasdfsdf");
-//
 //            }
 //        }catch (BusinessException e){
 //            log.error("发生了错误:{}", e.getMessage());

+ 2 - 0
4dkankan-center-scene/src/main/java/com/fdkankan/scene/service/ISceneEditInfoService.java

@@ -26,6 +26,8 @@ public interface ISceneEditInfoService extends IService<SceneEditInfo> {
 
     ResultData saveUpload(SaveUploadParamVO param) throws Exception;
 
+    ResultData saveCad(BaseDataParamVO param) throws Exception;
+
     void upgradeVersionById(Long id);
 
 }

+ 2 - 2
4dkankan-center-scene/src/main/java/com/fdkankan/scene/service/ISceneProService.java

@@ -6,7 +6,7 @@ import com.fdkankan.common.response.ResultData;
 import com.fdkankan.scene.entity.ScenePro;
 import com.fdkankan.scene.entity.SceneProPO;
 import com.fdkankan.scene.vo.SaveHotParamVO;
-import com.fdkankan.scene.vo.SaveRoamParamVO;
+import com.fdkankan.scene.vo.BaseDataParamVO;
 import com.fdkankan.scene.vo.SaveTagsVisibleParamVO;
 import com.fdkankan.scene.vo.SceneEditParamVO;
 import com.fdkankan.scene.vo.SceneParamVO;
@@ -94,7 +94,7 @@ public interface ISceneProService extends IService<ScenePro> {
 
     ResultData saveScreencapData(SceneEditParamVO base) throws Exception;
 
-    ResultData saveRoam(SaveRoamParamVO param) throws Exception;
+    ResultData saveRoam(BaseDataParamVO param) throws Exception;
 
     ResultData saveTagsVisible(SaveTagsVisibleParamVO param) throws Exception;
 

+ 78 - 2
4dkankan-center-scene/src/main/java/com/fdkankan/scene/service/impl/SceneEditInfoServiceImpl.java

@@ -3,6 +3,7 @@ package com.fdkankan.scene.service.impl;
 import cn.hutool.core.bean.BeanUtil;
 import cn.hutool.core.collection.CollUtil;
 import cn.hutool.core.util.StrUtil;
+import cn.hutool.json.JSONUtil;
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
@@ -12,6 +13,7 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import com.fdkankan.common.constant.*;
 import com.fdkankan.common.exception.BusinessException;
 import com.fdkankan.common.response.ResultData;
+import com.fdkankan.common.util.FileUtils;
 import com.fdkankan.fyun.oss.UploadToOssUtil;
 import com.fdkankan.redis.constant.RedisKey;
 import com.fdkankan.redis.util.RedisUtil;
@@ -19,6 +21,7 @@ import com.fdkankan.scene.bean.SceneJsonBean;
 import com.fdkankan.scene.entity.SceneEditControls;
 import com.fdkankan.scene.entity.SceneEditInfo;
 import com.fdkankan.scene.entity.ScenePro;
+import com.fdkankan.scene.entity.SceneProExt;
 import com.fdkankan.scene.factory.FloorLogoHandlerFactory;
 import com.fdkankan.scene.factory.FloorPlanHandlerFactory;
 import com.fdkankan.scene.factory.MusicHandlerFactory;
@@ -26,6 +29,7 @@ import com.fdkankan.scene.factory.ScreenshotHandlerFactory;
 import com.fdkankan.scene.mapper.ISceneEditInfoMapper;
 import com.fdkankan.scene.service.ISceneEditControlsService;
 import com.fdkankan.scene.service.ISceneEditInfoService;
+import com.fdkankan.scene.service.ISceneProExtService;
 import com.fdkankan.scene.service.ISceneProService;
 import com.fdkankan.scene.vo.*;
 import com.google.common.collect.Lists;
@@ -66,6 +70,8 @@ public class SceneEditInfoServiceImpl extends ServiceImpl<ISceneEditInfoMapper,
     private UploadToOssUtil uploadToOssUtil;
     @Autowired
     RedisUtil redisUtil;
+    @Autowired
+    private ISceneProExtService sceneProExtService;
 
 
     @Override
@@ -266,8 +272,8 @@ public class SceneEditInfoServiceImpl extends ServiceImpl<ISceneEditInfoMapper,
                 return new MusicHandlerFactory().getHandler().save(num, fileInfo);
             case FLOOR_LOGO:
                 return new FloorLogoHandlerFactory().getHandler().save(num, fileInfo);
-            case FLOOR_PLAN:
-                return new FloorPlanHandlerFactory().getHandler().save(num, fileInfo);
+//            case FLOOR_PLAN:
+//                return new FloorPlanHandlerFactory().getHandler().save(num, fileInfo);
             case SCREENSHOT:
                 return new ScreenshotHandlerFactory().getHandler().save(num, fileInfo);
 
@@ -278,6 +284,76 @@ public class SceneEditInfoServiceImpl extends ServiceImpl<ISceneEditInfoMapper,
     }
 
     @Override
+    public ResultData saveCad(BaseDataParamVO param) throws Exception {
+
+        String num = param.getNum();
+        ScenePro scenePro = sceneProService.findBySceneNum(num);
+        if(Objects.isNull(scenePro))
+            throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
+        JSONObject fileInfoJson = JSON.parseObject(param.getData());
+        //户型图文件路径
+        String cadInfo = fileInfoJson.getString("cadInfo");
+        String floorJsonData = fileInfoJson.getString("floorJsonData");
+
+        String filePaths = fileInfoJson.getString("filePaths");
+        cn.hutool.json.JSONArray filePathsArrs = JSONUtil.parseArray(filePaths);
+        List<String> filePathsList = filePathsArrs.toList(String.class);
+        StringBuilder filePathBuilder = new StringBuilder();
+        filePathsList.parallelStream().forEach(path -> {
+            filePathBuilder.append(",").append(path);
+        });
+
+
+        //写入数据库
+        SceneEditInfo sceneEditInfoDb = this.getBySceneProId(scenePro.getId());
+        if(Objects.nonNull(sceneEditInfoDb)){
+            this.update(new LambdaUpdateWrapper<SceneEditInfo>()
+                .setSql("version=version+"+1)
+                .set(SceneEditInfo::getFloorPlanPath, filePathBuilder.substring(1))
+                .set(SceneEditInfo::getCadInfo, cadInfo)
+                .eq(SceneEditInfo::getId, sceneEditInfoDb.getId()));
+        }else{
+            sceneEditInfoDb = new SceneEditInfo();
+            sceneEditInfoDb.setSceneProId(scenePro.getId());
+            sceneEditInfoDb.setFloorPlanPath(filePaths);
+            sceneEditInfoDb.setCadInfo(cadInfo);
+            this.save(sceneEditInfoDb);
+        }
+
+        //上传houst_floor.json文件
+        String localDataPath = String.format(ConstantFilePath.DATABUFFER_FORMAT, num);
+        String dataPath = String.format(UploadFilePath.DATA_VIEW_PATH, num);
+
+        // TODO: 2022/1/27 旧版本目录,待删除
+        String oldDataPath = String.format(ConstantFilePath.DATA_PATH_FORMAT, num);
+
+        if(StrUtil.isEmpty(floorJsonData)){
+            if(scenePro == null){
+                throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
+            }
+            SceneProExt sceneProExt = sceneProExtService.findBySceneProId(scenePro.getId());
+            // TODO: 2022/1/27 老版本数据目录挂在nas,新版本目前流程尚不清楚,先暂时按照老版本写,以后再调整
+            FileUtils.copyFile(sceneProExt.getDataSource() + "/results/floor.json", localDataPath + "houst_floor.json", true);
+            uploadToOssUtil.upload(localDataPath + "houst_floor.json", dataPath + "houst_floor.json");
+
+            // TODO: 2022/1/27 老版本上传目录 待删除
+            uploadToOssUtil.upload(localDataPath + "houst_floor.json", oldDataPath + "houst_floor.json");
+
+            String result = FileUtils.readFile(localDataPath + "houst_floor.json");
+            return ResultData.ok(result);
+        }
+
+        FileUtils.writeFile(localDataPath + "houst_floor.json", floorJsonData);
+        uploadToOssUtil.upload(localDataPath + "houst_floor.json", dataPath + "houst_floor.json");
+
+        // TODO: 2022/1/27 老版本上传目录 待删除
+        uploadToOssUtil.upload(localDataPath + "houst_floor.json", oldDataPath + "houst_floor.json");
+
+        return ResultData.ok();
+
+    }
+
+    @Override
     public void upgradeVersionById(Long id) {
         this.update(new LambdaUpdateWrapper<SceneEditInfo>()
             .setSql("version=version+" + 1)

+ 1 - 8
4dkankan-center-scene/src/main/java/com/fdkankan/scene/service/impl/SceneProServiceImpl.java

@@ -4,16 +4,9 @@ import cn.hutool.core.bean.BeanUtil;
 import cn.hutool.core.collection.CollUtil;
 import cn.hutool.core.date.DateUtil;
 import cn.hutool.core.util.StrUtil;
-import cn.hutool.json.JSONUtil;
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
-import com.aliyun.oss.OSSClient;
-import com.aliyun.oss.model.ListObjectsRequest;
-import com.aliyun.oss.model.OSSObjectSummary;
-import com.aliyun.oss.model.ObjectListing;
-import com.aliyun.oss.model.ObjectMetadata;
-import com.amazonaws.services.storagegateway.model.StorageGatewayError;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
@@ -2688,7 +2681,7 @@ public class SceneProServiceImpl extends ServiceImpl<ISceneProMapper, ScenePro>
 
     @Override
 //    @SystemServiceLog(description = "漫游可行")
-    public ResultData saveRoam(SaveRoamParamVO param) throws Exception {
+    public ResultData saveRoam(BaseDataParamVO param) throws Exception {
 
         ScenePro scenePro = this.findBySceneNum(param.getNum());
         if (scenePro == null ) {

+ 3 - 3
4dkankan-center-scene/src/main/java/com/fdkankan/scene/vo/SaveRoamParamVO.java

@@ -6,19 +6,19 @@ import lombok.Data;
 
 /**
  * <p>
- * 保存漫游可行入参
+ * 通用data类型参数类
  * </p>
  *
  * @author dengsixing
  * @since 2022/2/10
  **/
 @Data
-public class SaveRoamParamVO {
+public class BaseDataParamVO {
 
     @NotBlank(message = "场景码不能为空")
     private String num;
 
-    @NotBlank(message = "漫游可行数据不能为空")
+    @NotBlank(message = "数据不能为空")
     private String data;
 
 }

+ 2 - 1
4dkankan-center-scene/src/main/resources/META-INF/services/com.alibaba.csp.sentinel.init.InitFunc

@@ -1 +1,2 @@
-com.fdkankan.common.config.SentinelDataSourceInitFunc
+#如果用本地文件的作为sentinel数据持久化,需要在这里写明持久化逻辑实现类是哪个
+#com.fdkankan.common.config.SentinelFileDataSourceInitFunc

+ 22 - 1
4dkankan-center-scene/src/main/resources/bootstrap.yml

@@ -4,7 +4,7 @@ spring:
       #关闭jackson转换 实体属性空值校验
       FAIL_ON_EMPTY_BEANS: false
   application:
-    name: 4dkankan-center-scene
+    name: 4dkankan-scene
   servlet:
     multipart:
       # 设置单个文件大小
@@ -47,9 +47,30 @@ spring:
     sentinel:
       transport:
         dashboard: 192.168.0.47:8888
+#        dashboard: localhost:8888
         heartbeat-interval-ms: 500
         port: 8719
       eager: true #取消sentinel控制台懒加载
+      #sentinel配置持久化nacos
+      datasource:
+        #流控规则
+        flow:
+          nacos:
+            server-addr: ${spring.cloud.nacos.config.server-addr}
+            dataId: ${spring.application.name}-flow-rules
+            groupId: SENTINEL_GROUP
+            namespace: 4dkankan-dev
+#            data-type: json
+            rule-type: flow
+        #熔断规则
+        degrade:
+          nacos:
+            server-addr: ${spring.cloud.nacos.config.server-addr}
+            dataId: ${spring.application.name}-degrade-rules
+            groupId: SENTINEL_GROUP
+            namespace: 4dkankan-dev
+#            data-type: json
+            rule-type: degrade
 #      log:
 #        dir: ./logs # 默认值${home}/logs/csp/
 #        switch-pid: true # 日志带上线程id

+ 0 - 156
4dkankan-common/src/main/java/com/fdkankan/common/config/SentinelDataSourceInitFunc.java

@@ -1,156 +0,0 @@
-package com.fdkankan.common.config;
-
-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;
-
-/**
- * <p>
- * sentinel规则数据持久化到本地文件
- * </p>
- *
- * @author dengsixing
- * @since 2022/1/26
- **/
-public class SentinelDataSourceInitFunc implements InitFunc {
-
-    @Override
-    public void init() throws Exception {
-        //持久化在本地的目录
-        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 paramFlowRulePath = ruleDir + "/param-flow-rule.json";
-
-        this.mkdirIfNotExits(ruleDir);
-        this.createFileIfNotExits(flowRulePath);
-        this.createFileIfNotExits(degradeRulePath);
-        this.createFileIfNotExits(systemRulePath);
-        this.createFileIfNotExits(authorityRulePath);
-        this.createFileIfNotExits(paramFlowRulePath);
-
-        // 流控规则
-        ReadableDataSource<String, List<FlowRule>> flowRuleRDS = new FileRefreshableDataSource<>(
-                flowRulePath,
-                flowRuleListParser
-        );
-        // 将可读数据源注册至FlowRuleManager
-        // 这样当规则文件发生变化时,就会更新规则到内存
-        FlowRuleManager.register2Property(flowRuleRDS.getProperty());
-        WritableDataSource<List<FlowRule>> flowRuleWDS = new FileWritableDataSource<List<FlowRule>>(
-                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>> paramFlowRuleRDS = new FileRefreshableDataSource<>(
-                paramFlowRulePath,
-                paramFlowRuleListParser
-        );
-        ParamFlowRuleManager.register2Property(paramFlowRuleRDS.getProperty());
-        WritableDataSource<List<ParamFlowRule>> paramFlowRuleWDS = new FileWritableDataSource<>(
-                paramFlowRulePath,
-                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>> paramFlowRuleListParser = source -> JSON.parseObject(
-            source,
-            new TypeReference<List<ParamFlowRule>>() {}
-    );
-
-    private void mkdirIfNotExits(String filePath) throws IOException {
-        File file = new File(filePath);
-        if (!file.exists()) {
-            file.mkdirs();
-        }
-    }
-
-    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);
-    }
-}

+ 156 - 0
4dkankan-common/src/main/java/com/fdkankan/common/config/SentinelFileDataSourceInitFunc.java

@@ -0,0 +1,156 @@
+//package com.fdkankan.common.config;
+//
+//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;
+//
+///**
+// * <p>
+// * sentinel规则数据持久化到本地文件
+// * </p>
+// *
+// * @author dengsixing
+// * @since 2022/1/26
+// **/
+//public class SentinelFileDataSourceInitFunc implements InitFunc {
+//
+//    @Override
+//    public void init() throws Exception {
+//        //持久化在本地的目录
+//        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 paramFlowRulePath = ruleDir + "/param-flow-rule.json";
+//
+//        this.mkdirIfNotExits(ruleDir);
+//        this.createFileIfNotExits(flowRulePath);
+//        this.createFileIfNotExits(degradeRulePath);
+//        this.createFileIfNotExits(systemRulePath);
+//        this.createFileIfNotExits(authorityRulePath);
+//        this.createFileIfNotExits(paramFlowRulePath);
+//
+//        // 流控规则
+//        ReadableDataSource<String, List<FlowRule>> flowRuleRDS = new FileRefreshableDataSource<>(
+//                flowRulePath,
+//                flowRuleListParser
+//        );
+//        // 将可读数据源注册至FlowRuleManager
+//        // 这样当规则文件发生变化时,就会更新规则到内存
+//        FlowRuleManager.register2Property(flowRuleRDS.getProperty());
+//        WritableDataSource<List<FlowRule>> flowRuleWDS = new FileWritableDataSource<List<FlowRule>>(
+//                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>> paramFlowRuleRDS = new FileRefreshableDataSource<>(
+//                paramFlowRulePath,
+//                paramFlowRuleListParser
+//        );
+//        ParamFlowRuleManager.register2Property(paramFlowRuleRDS.getProperty());
+//        WritableDataSource<List<ParamFlowRule>> paramFlowRuleWDS = new FileWritableDataSource<>(
+//                paramFlowRulePath,
+//                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>> paramFlowRuleListParser = source -> JSON.parseObject(
+//            source,
+//            new TypeReference<List<ParamFlowRule>>() {}
+//    );
+//
+//    private void mkdirIfNotExits(String filePath) throws IOException {
+//        File file = new File(filePath);
+//        if (!file.exists()) {
+//            file.mkdirs();
+//        }
+//    }
+//
+//    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);
+//    }
+//}