Sentinel1.8.6更改配置同步到nacos(项目是Gateway)

本次修改的源码在:https://gitee.com/stonic-open-source/sentinel-parent

下载源码 地址:https://github.com/alibaba/Sentinel/releases/tag/1.8.6

导入idea,等待maven下载好各种依赖

打开sentile-dashboard这个模块,打开resources下的application.properties配置

把下列配置加进去

#你的nacos地址
nacos.server-addr=localhost:8148  
#准备把sentinel配置同步到的nacos命名空间
nacos.namespace=zixun_dev 
#你的nacos用户名
nacos.username=nacos 
#你的nacos密码
nacos.password=nacos 

打开sentile-dashboard下的pom,把sentinel-datasource-nacos的<scope>test</scope>删掉(记得刷新一下maven)

刷新maven

rule文件夹下新建一个nacos目录

把图中test的NacosConfig和Util复制到nacos目录下

然后在nacos下新建一个NacosInfoConfig类,用于读取配置文件

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;/*** @author 刘辉* @description* @since 2024/5/17 上午10:26*/
@Component
@ConfigurationProperties(prefix = "nacos")
public class NacosInfoConfig {private String serverAddr;private String username;private String password;private String namespace;public String getServerAddr() {return serverAddr;}public void setServerAddr(String serverAddr) {this.serverAddr = serverAddr;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getNamespace() {return namespace;}public void setNamespace(String namespace) {this.namespace = namespace;}
}

然后修改一下NacosConfigUtil的内容  其中group_id需要和你springcloud项目配置的nacos中sentinel的groupId一致

public final class NacosConfigUtil {/*** 同步到nacos生成的groupId 没有可不填*/public static final String GROUP_ID = "zixun_sentinel";/*** 同步到nacos生成的sentinel api规则的后缀*/public static final String API_DATA_ID_POSTFIX = "-api-rules";/*** 同步到nacos生成的sentinel 流控规则的后缀*/public static final String FLOW_DATA_ID_POSTFIX = "-flow-rules";/*** 同步到nacos生成的sentinel 参数规则的后缀*/public static final String PARAM_FLOW_DATA_ID_POSTFIX = "-param-rules";public static final String CLUSTER_MAP_DATA_ID_POSTFIX = "-cluster-map";/*** cc for `cluster-client`*/public static final String CLIENT_CONFIG_DATA_ID_POSTFIX = "-cc-config";/*** cs for `cluster-server`*/public static final String SERVER_TRANSPORT_CONFIG_DATA_ID_POSTFIX = "-cs-transport-config";public static final String SERVER_FLOW_CONFIG_DATA_ID_POSTFIX = "-cs-flow-config";public static final String SERVER_NAMESPACE_SET_DATA_ID_POSTFIX = "-cs-namespace-set";private NacosConfigUtil() {}
}

修改NacosConfig文件

将配置的nacos信息注入进去,且新增gateway流控配置和sentinel全局规则的配置

import java.util.List;
import java.util.Properties;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.ApiDefinitionEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayFlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.ConfigFactory;
import com.alibaba.nacos.api.config.ConfigService;/*** @author Eric Zhao* @since 1.4.0*/
@Configuration
public class NacosConfig {@Autowiredprivate NacosInfoConfig nacosInfoConfig;/*** sentinel本地流控 编码器* @return*/@Beanpublic Converter<List<FlowRuleEntity>, String> flowRuleEntityEncoder() {return JSON::toJSONString;}/*** sentinel 针对gateway流控配置 编码器* @return*/@Beanpublic Converter<List<GatewayFlowRuleEntity>, String> flowRuleGatewayEntityEncoder() {return JSON::toJSONString;}/*** sentinel 针对全局流控配置 编码器* @return*/@Beanpublic Converter<List<ApiDefinitionEntity>, String> flowRuleNacosEntityEncoder() {return JSON::toJSONString;}/*** sentinel本地流控 解码器* @return*/@Beanpublic Converter<String, List<FlowRuleEntity>> flowRuleEntityDecoder() {return s -> JSON.parseArray(s, FlowRuleEntity.class);}/*** sentinel 针对gateway流控配置 解码器* @return*/@Beanpublic Converter<String, List<GatewayFlowRuleEntity>> flowRuleGatewayEntityDecoder() {return s -> JSON.parseArray(s, GatewayFlowRuleEntity.class);}/*** sentinel 针对全局流控配置 解码器* @return*/@Beanpublic Converter<String, List<ApiDefinitionEntity>> flowRuleNacosEntityDecoder() {return s -> JSON.parseArray(s, ApiDefinitionEntity.class);}@Beanpublic ConfigService nacosConfigService() throws Exception {Properties properties = new Properties();//Nacos地址properties.put("serverAddr", nacosInfoConfig.getServerAddr());//Nacos用户名properties.put("username", nacosInfoConfig.getUsername());//Nacos密码properties.put("password", nacosInfoConfig.getPassword());properties.put("namespace", nacosInfoConfig.getNamespace());return ConfigFactory.createConfigService(properties);}
}

新建FlowRuleGatewayProvider和FlowRuleGatewayPublisher  分别提供gateway添加和查询的操作

import java.util.ArrayList;
import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayFlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosConfigUtil;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.nacos.api.config.ConfigService;/*** @author Eric Zhao* @since 1.4.0*/
@Component("flowRuleGatewayProvider")
public class FlowRuleGatewayProvider implements DynamicRuleProvider<List<GatewayFlowRuleEntity>> {@Autowiredprivate ConfigService configService;@Autowired@Qualifier("flowRuleGatewayEntityDecoder")private Converter<String, List<GatewayFlowRuleEntity>> converter;@Overridepublic List<GatewayFlowRuleEntity> getRules(String appName) throws Exception {String rules = configService.getConfig(appName + NacosConfigUtil.FLOW_DATA_ID_POSTFIX,NacosConfigUtil.GROUP_ID, 3000);if (StringUtil.isEmpty(rules)) {return new ArrayList<>();}return converter.convert(rules);}
}
import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayFlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosConfigUtil;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.ConfigType;/*** @author Eric Zhao* @since 1.4.0*/
@Component("flowRuleGatewayPublisher")
public class FlowRuleGatewayPublisher implements DynamicRulePublisher<List<GatewayFlowRuleEntity>> {@Autowiredprivate ConfigService configService;@Autowired@Qualifier("flowRuleGatewayEntityEncoder")private Converter<List<GatewayFlowRuleEntity>, String> converter;@Overridepublic void publish(String app, List<GatewayFlowRuleEntity> rules) throws Exception {AssertUtil.notEmpty(app, "app name cannot be empty");if (rules == null) {return;}configService.publishConfig(app + NacosConfigUtil.FLOW_DATA_ID_POSTFIX,NacosConfigUtil.GROUP_ID, converter.convert(rules), ConfigType.JSON.getType());}
}

新建FlowRuleApiProvider和FlowRuleApiPublisher  分别提供sentinel全局规则 查询和编辑

import java.util.ArrayList;
import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.ApiDefinitionEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosConfigUtil;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.nacos.api.config.ConfigService;/*** @author Eric Zhao* @since 1.4.0*/
@Component("flowRuleNacosProvider")
public class FlowRuleApiProvider implements DynamicRuleProvider<List<ApiDefinitionEntity>> {@Autowiredprivate ConfigService configService;@Autowired@Qualifier("flowRuleNacosEntityDecoder")private Converter<String, List<ApiDefinitionEntity>> converter;@Overridepublic List<ApiDefinitionEntity> getRules(String appName) throws Exception {String rules = configService.getConfig(appName + NacosConfigUtil.API_DATA_ID_POSTFIX,NacosConfigUtil.GROUP_ID, 3000);if (StringUtil.isEmpty(rules)) {return new ArrayList<>();}return converter.convert(rules);}
}
import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.ApiDefinitionEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosConfigUtil;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.ConfigType;/*** @author Eric Zhao* @since 1.4.0*/
@Component("flowRuleNacosPublisher")
public class FlowRuleApiPublisher implements DynamicRulePublisher<List<ApiDefinitionEntity>> {@Autowiredprivate ConfigService configService;@Autowired@Qualifier("flowRuleNacosEntityEncoder")private Converter<List<ApiDefinitionEntity>, String> converter;@Overridepublic void publish(String app, List<ApiDefinitionEntity> rules) throws Exception {AssertUtil.notEmpty(app, "app name cannot be empty");if (rules == null) {return;}configService.publishConfig(app + NacosConfigUtil.API_DATA_ID_POSTFIX,NacosConfigUtil.GROUP_ID, converter.convert(rules), ConfigType.JSON.getType());}
}

自此配置方面就结束了,接下来上controller代码

找到controller下的gateway目录两个controller

下边的增删改查方法都有修改,修改的地方比较多,这里我直接贴主要替换的代码和controller全部代码大家直接粘贴

GatewayApiController修改处:
 

    @Autowired@Qualifier("flowRuleNacosProvider")private DynamicRuleProvider<List<ApiDefinitionEntity>> ruleProvider;@Autowired@Qualifier("flowRuleNacosPublisher")private DynamicRulePublisher<List<ApiDefinitionEntity>> rulePublisher;

package com.alibaba.csp.sentinel.dashboard.controller.gateway;import com.alibaba.csp.sentinel.dashboard.auth.AuthAction;
import com.alibaba.csp.sentinel.dashboard.auth.AuthService;
import com.alibaba.csp.sentinel.dashboard.client.SentinelApiClient;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.ApiDefinitionEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.ApiPredicateItemEntity;
import com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo;
import com.alibaba.csp.sentinel.dashboard.domain.Result;
import com.alibaba.csp.sentinel.dashboard.domain.vo.gateway.api.AddApiReqVo;
import com.alibaba.csp.sentinel.dashboard.domain.vo.gateway.api.ApiPredicateItemVo;
import com.alibaba.csp.sentinel.dashboard.domain.vo.gateway.api.UpdateApiReqVo;
import com.alibaba.csp.sentinel.dashboard.repository.gateway.InMemApiDefinitionStore;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;import javax.servlet.http.HttpServletRequest;
import java.util.*;import static com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants.*;/*** Gateway api Controller for manage gateway api definitions.** @author cdfive* @since 1.7.0*/
@RestController
@RequestMapping(value = "/gateway/api")
public class GatewayApiController {private final Logger logger = LoggerFactory.getLogger(GatewayApiController.class);@Autowiredprivate InMemApiDefinitionStore repository;@Autowiredprivate SentinelApiClient sentinelApiClient;@Autowired@Qualifier("flowRuleNacosProvider")private DynamicRuleProvider<List<ApiDefinitionEntity>> ruleProvider;@Autowired@Qualifier("flowRuleNacosPublisher")private DynamicRulePublisher<List<ApiDefinitionEntity>> rulePublisher;@GetMapping("/list.json")@AuthAction(AuthService.PrivilegeType.READ_RULE)public Result<List<ApiDefinitionEntity>> queryApis(String app, String ip, Integer port) {if (StringUtil.isEmpty(app)) {return Result.ofFail(-1, "app can't be null or empty");}if (StringUtil.isEmpty(ip)) {return Result.ofFail(-1, "ip can't be null or empty");}if (port == null) {return Result.ofFail(-1, "port can't be null");}try {List<ApiDefinitionEntity> apis = ruleProvider.getRules(app);
//            List<ApiDefinitionEntity> apis = sentinelApiClient.fetchApis(app, ip, port).get();repository.saveAll(apis);return Result.ofSuccess(apis);} catch (Throwable throwable) {logger.error("queryApis error:", throwable);return Result.ofThrowable(-1, throwable);}}@PostMapping("/new.json")@AuthAction(AuthService.PrivilegeType.WRITE_RULE)public Result<ApiDefinitionEntity> addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo) {String app = reqVo.getApp();if (StringUtil.isBlank(app)) {return Result.ofFail(-1, "app can't be null or empty");}ApiDefinitionEntity entity = new ApiDefinitionEntity();entity.setApp(app.trim());String ip = reqVo.getIp();if (StringUtil.isBlank(ip)) {return Result.ofFail(-1, "ip can't be null or empty");}entity.setIp(ip.trim());Integer port = reqVo.getPort();if (port == null) {return Result.ofFail(-1, "port can't be null");}entity.setPort(port);// API名称String apiName = reqVo.getApiName();if (StringUtil.isBlank(apiName)) {return Result.ofFail(-1, "apiName can't be null or empty");}entity.setApiName(apiName.trim());// 匹配规则列表List<ApiPredicateItemVo> predicateItems = reqVo.getPredicateItems();if (CollectionUtils.isEmpty(predicateItems)) {return Result.ofFail(-1, "predicateItems can't empty");}List<ApiPredicateItemEntity> predicateItemEntities = new ArrayList<>();for (ApiPredicateItemVo predicateItem : predicateItems) {ApiPredicateItemEntity predicateItemEntity = new ApiPredicateItemEntity();// 匹配模式Integer matchStrategy = predicateItem.getMatchStrategy();if (!Arrays.asList(URL_MATCH_STRATEGY_EXACT, URL_MATCH_STRATEGY_PREFIX, URL_MATCH_STRATEGY_REGEX).contains(matchStrategy)) {return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy);}predicateItemEntity.setMatchStrategy(matchStrategy);// 匹配串String pattern = predicateItem.getPattern();if (StringUtil.isBlank(pattern)) {return Result.ofFail(-1, "pattern can't be null or empty");}predicateItemEntity.setPattern(pattern);predicateItemEntities.add(predicateItemEntity);}entity.setPredicateItems(new LinkedHashSet<>(predicateItemEntities));// 检查API名称不能重复List<ApiDefinitionEntity> allApis = repository.findAllByMachine(MachineInfo.of(app.trim(), ip.trim(), port));if (allApis.stream().map(o -> o.getApiName()).anyMatch(o -> o.equals(apiName.trim()))) {return Result.ofFail(-1, "apiName exists: " + apiName);}Date date = new Date();entity.setGmtCreate(date);entity.setGmtModified(date);try {entity = repository.save(entity);publishApis(entity.getApp());} catch (Throwable throwable) {logger.error("add gateway api error:", throwable);return Result.ofThrowable(-1, throwable);}//        if (!publishApis(app, ip, port)) {
//            logger.warn("publish gateway apis fail after add");
//        }return Result.ofSuccess(entity);}@PostMapping("/save.json")@AuthAction(AuthService.PrivilegeType.WRITE_RULE)public Result<ApiDefinitionEntity> updateApi(@RequestBody UpdateApiReqVo reqVo) {String app = reqVo.getApp();if (StringUtil.isBlank(app)) {return Result.ofFail(-1, "app can't be null or empty");}Long id = reqVo.getId();if (id == null) {return Result.ofFail(-1, "id can't be null");}ApiDefinitionEntity entity = repository.findById(id);if (entity == null) {return Result.ofFail(-1, "api does not exist, id=" + id);}// 匹配规则列表List<ApiPredicateItemVo> predicateItems = reqVo.getPredicateItems();if (CollectionUtils.isEmpty(predicateItems)) {return Result.ofFail(-1, "predicateItems can't empty");}List<ApiPredicateItemEntity> predicateItemEntities = new ArrayList<>();for (ApiPredicateItemVo predicateItem : predicateItems) {ApiPredicateItemEntity predicateItemEntity = new ApiPredicateItemEntity();// 匹配模式int matchStrategy = predicateItem.getMatchStrategy();if (!Arrays.asList(URL_MATCH_STRATEGY_EXACT, URL_MATCH_STRATEGY_PREFIX, URL_MATCH_STRATEGY_REGEX).contains(matchStrategy)) {return Result.ofFail(-1, "Invalid matchStrategy: " + matchStrategy);}predicateItemEntity.setMatchStrategy(matchStrategy);// 匹配串String pattern = predicateItem.getPattern();if (StringUtil.isBlank(pattern)) {return Result.ofFail(-1, "pattern can't be null or empty");}predicateItemEntity.setPattern(pattern);predicateItemEntities.add(predicateItemEntity);}entity.setPredicateItems(new LinkedHashSet<>(predicateItemEntities));Date date = new Date();entity.setGmtModified(date);try {entity = repository.save(entity);publishApis(entity.getApp());} catch (Throwable throwable) {logger.error("update gateway api error:", throwable);return Result.ofThrowable(-1, throwable);}//        if (!publishApis(app, entity.getIp(), entity.getPort())) {
//            logger.warn("publish gateway apis fail after update");
//        }return Result.ofSuccess(entity);}@PostMapping("/delete.json")@AuthAction(AuthService.PrivilegeType.DELETE_RULE)public Result<Long> deleteApi(Long id) {if (id == null) {return Result.ofFail(-1, "id can't be null");}ApiDefinitionEntity oldEntity = repository.findById(id);if (oldEntity == null) {return Result.ofSuccess(null);}try {repository.delete(id);publishApis(oldEntity.getApp());} catch (Throwable throwable) {logger.error("delete gateway api error:", throwable);return Result.ofThrowable(-1, throwable);}//        if (!publishApis(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) {
//            logger.warn("publish gateway apis fail after delete");
//        }return Result.ofSuccess(id);}//    private boolean publishApis(String app, String ip, Integer port) {
//        List<ApiDefinitionEntity> apis = repository.findAllByMachine(MachineInfo.of(app, ip, port));
//        return sentinelApiClient.modifyApis(app, ip, port, apis);
//    }private void publishApis(/*@NonNull*/ String app) throws Exception {List<ApiDefinitionEntity> rules = repository.findAllByApp(app);rulePublisher.publish(app, rules);}
}

GatewayFlowRuleController修改为:

    @Autowired@Qualifier("flowRuleGatewayProvider")private DynamicRuleProvider<List<GatewayFlowRuleEntity>> ruleProvider;@Autowired@Qualifier("flowRuleGatewayPublisher")private DynamicRulePublisher<List<GatewayFlowRuleEntity>> rulePublisher;

package com.alibaba.csp.sentinel.dashboard.controller.gateway;import com.alibaba.csp.sentinel.dashboard.auth.AuthAction;
import com.alibaba.csp.sentinel.dashboard.auth.AuthService;
import com.alibaba.csp.sentinel.dashboard.client.SentinelApiClient;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayFlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayParamFlowItemEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo;
import com.alibaba.csp.sentinel.dashboard.domain.Result;
import com.alibaba.csp.sentinel.dashboard.domain.vo.gateway.rule.AddFlowRuleReqVo;
import com.alibaba.csp.sentinel.dashboard.domain.vo.gateway.rule.GatewayParamFlowItemVo;
import com.alibaba.csp.sentinel.dashboard.domain.vo.gateway.rule.UpdateFlowRuleReqVo;
import com.alibaba.csp.sentinel.dashboard.repository.gateway.InMemGatewayFlowRuleStore;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;import java.util.Arrays;
import java.util.Date;
import java.util.List;import static com.alibaba.csp.sentinel.slots.block.RuleConstant.*;
import static com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants.*;
import static com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayFlowRuleEntity.*;/*** Gateway flow rule Controller for manage gateway flow rules.** @author cdfive* @since 1.7.0*/
@RestController
@RequestMapping(value = "/gateway/flow")
public class GatewayFlowRuleController {private final Logger logger = LoggerFactory.getLogger(GatewayFlowRuleController.class);@Autowiredprivate InMemGatewayFlowRuleStore repository;@Autowiredprivate SentinelApiClient sentinelApiClient;@Autowired@Qualifier("flowRuleGatewayProvider")private DynamicRuleProvider<List<GatewayFlowRuleEntity>> ruleProvider;@Autowired@Qualifier("flowRuleGatewayPublisher")private DynamicRulePublisher<List<GatewayFlowRuleEntity>> rulePublisher;@GetMapping("/list.json")@AuthAction(AuthService.PrivilegeType.READ_RULE)public Result<List<GatewayFlowRuleEntity>> queryFlowRules(String app, String ip, Integer port) {if (StringUtil.isEmpty(app)) {return Result.ofFail(-1, "app can't be null or empty");}if (StringUtil.isEmpty(ip)) {return Result.ofFail(-1, "ip can't be null or empty");}if (port == null) {return Result.ofFail(-1, "port can't be null");}//        try {
//            List<GatewayFlowRuleEntity> rules = sentinelApiClient.fetchGatewayFlowRules(app, ip, port).get();
//            repository.saveAll(rules);
//            return Result.ofSuccess(rules);
//        } catch (Throwable throwable) {
//            logger.error("query gateway flow rules error:", throwable);
//            return Result.ofThrowable(-1, throwable);
//        }try {List<GatewayFlowRuleEntity> rules = ruleProvider.getRules(app);rules = repository.saveAll(rules);return Result.ofSuccess(rules);} catch (Throwable throwable) {logger.error("Error when querying flow rules", throwable);return Result.ofThrowable(-1, throwable);}}@PostMapping("/new.json")@AuthAction(AuthService.PrivilegeType.WRITE_RULE)public Result<GatewayFlowRuleEntity> addFlowRule(@RequestBody AddFlowRuleReqVo reqVo) {String app = reqVo.getApp();if (StringUtil.isBlank(app)) {return Result.ofFail(-1, "app can't be null or empty");}GatewayFlowRuleEntity entity = new GatewayFlowRuleEntity();entity.setApp(app.trim());String ip = reqVo.getIp();if (StringUtil.isBlank(ip)) {return Result.ofFail(-1, "ip can't be null or empty");}entity.setIp(ip.trim());Integer port = reqVo.getPort();if (port == null) {return Result.ofFail(-1, "port can't be null");}entity.setPort(port);// API类型, Route ID或API分组Integer resourceMode = reqVo.getResourceMode();if (resourceMode == null) {return Result.ofFail(-1, "resourceMode can't be null");}if (!Arrays.asList(RESOURCE_MODE_ROUTE_ID, RESOURCE_MODE_CUSTOM_API_NAME).contains(resourceMode)) {return Result.ofFail(-1, "invalid resourceMode: " + resourceMode);}entity.setResourceMode(resourceMode);// API名称String resource = reqVo.getResource();if (StringUtil.isBlank(resource)) {return Result.ofFail(-1, "resource can't be null or empty");}entity.setResource(resource.trim());// 针对请求属性GatewayParamFlowItemVo paramItem = reqVo.getParamItem();if (paramItem != null) {GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity();entity.setParamItem(itemEntity);// 参数属性 0-ClientIP 1-Remote Host 2-Header 3-URL参数 4-CookieInteger parseStrategy = paramItem.getParseStrategy();if (!Arrays.asList(PARAM_PARSE_STRATEGY_CLIENT_IP, PARAM_PARSE_STRATEGY_HOST, PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) {return Result.ofFail(-1, "invalid parseStrategy: " + parseStrategy);}itemEntity.setParseStrategy(paramItem.getParseStrategy());// 当参数属性为2-Header 3-URL参数 4-Cookie时,参数名称必填if (Arrays.asList(PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) {// 参数名称String fieldName = paramItem.getFieldName();if (StringUtil.isBlank(fieldName)) {return Result.ofFail(-1, "fieldName can't be null or empty");}itemEntity.setFieldName(paramItem.getFieldName());}String pattern = paramItem.getPattern();// 如果匹配串不为空,验证匹配模式if (StringUtil.isNotEmpty(pattern)) {itemEntity.setPattern(pattern);Integer matchStrategy = paramItem.getMatchStrategy();if (!Arrays.asList(PARAM_MATCH_STRATEGY_EXACT, PARAM_MATCH_STRATEGY_CONTAINS, PARAM_MATCH_STRATEGY_REGEX).contains(matchStrategy)) {return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy);}itemEntity.setMatchStrategy(matchStrategy);}}// 阈值类型 0-线程数 1-QPSInteger grade = reqVo.getGrade();if (grade == null) {return Result.ofFail(-1, "grade can't be null");}if (!Arrays.asList(FLOW_GRADE_THREAD, FLOW_GRADE_QPS).contains(grade)) {return Result.ofFail(-1, "invalid grade: " + grade);}entity.setGrade(grade);// QPS阈值Double count = reqVo.getCount();if (count == null) {return Result.ofFail(-1, "count can't be null");}if (count < 0) {return Result.ofFail(-1, "count should be at lease zero");}entity.setCount(count);// 间隔Long interval = reqVo.getInterval();if (interval == null) {return Result.ofFail(-1, "interval can't be null");}if (interval <= 0) {return Result.ofFail(-1, "interval should be greater than zero");}entity.setInterval(interval);// 间隔单位Integer intervalUnit = reqVo.getIntervalUnit();if (intervalUnit == null) {return Result.ofFail(-1, "intervalUnit can't be null");}if (!Arrays.asList(INTERVAL_UNIT_SECOND, INTERVAL_UNIT_MINUTE, INTERVAL_UNIT_HOUR, INTERVAL_UNIT_DAY).contains(intervalUnit)) {return Result.ofFail(-1, "Invalid intervalUnit: " + intervalUnit);}entity.setIntervalUnit(intervalUnit);// 流控方式 0-快速失败 2-匀速排队Integer controlBehavior = reqVo.getControlBehavior();if (controlBehavior == null) {return Result.ofFail(-1, "controlBehavior can't be null");}if (!Arrays.asList(CONTROL_BEHAVIOR_DEFAULT, CONTROL_BEHAVIOR_RATE_LIMITER).contains(controlBehavior)) {return Result.ofFail(-1, "invalid controlBehavior: " + controlBehavior);}entity.setControlBehavior(controlBehavior);if (CONTROL_BEHAVIOR_DEFAULT == controlBehavior) {// 0-快速失败, 则Burst size必填Integer burst = reqVo.getBurst();if (burst == null) {return Result.ofFail(-1, "burst can't be null");}if (burst < 0) {return Result.ofFail(-1, "invalid burst: " + burst);}entity.setBurst(burst);} else if (CONTROL_BEHAVIOR_RATE_LIMITER == controlBehavior) {// 1-匀速排队, 则超时时间必填Integer maxQueueingTimeoutMs = reqVo.getMaxQueueingTimeoutMs();if (maxQueueingTimeoutMs == null) {return Result.ofFail(-1, "maxQueueingTimeoutMs can't be null");}if (maxQueueingTimeoutMs < 0) {return Result.ofFail(-1, "invalid maxQueueingTimeoutMs: " + maxQueueingTimeoutMs);}entity.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs);}Date date = new Date();entity.setGmtCreate(date);entity.setGmtModified(date);try {entity = repository.save(entity);publishRules(entity.getApp());} catch (Throwable throwable) {logger.error("add gateway flow rule error:", throwable);return Result.ofThrowable(-1, throwable);}//        if (!publishRules(app, ip, port)) {
//            logger.warn("publish gateway flow rules fail after add");
//        }return Result.ofSuccess(entity);}@PostMapping("/save.json")@AuthAction(AuthService.PrivilegeType.WRITE_RULE)public Result<GatewayFlowRuleEntity> updateFlowRule(@RequestBody UpdateFlowRuleReqVo reqVo) {String app = reqVo.getApp();if (StringUtil.isBlank(app)) {return Result.ofFail(-1, "app can't be null or empty");}Long id = reqVo.getId();if (id == null) {return Result.ofFail(-1, "id can't be null");}GatewayFlowRuleEntity entity = repository.findById(id);if (entity == null) {return Result.ofFail(-1, "gateway flow rule does not exist, id=" + id);}// 针对请求属性GatewayParamFlowItemVo paramItem = reqVo.getParamItem();if (paramItem != null) {GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity();entity.setParamItem(itemEntity);// 参数属性 0-ClientIP 1-Remote Host 2-Header 3-URL参数 4-CookieInteger parseStrategy = paramItem.getParseStrategy();if (!Arrays.asList(PARAM_PARSE_STRATEGY_CLIENT_IP, PARAM_PARSE_STRATEGY_HOST, PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) {return Result.ofFail(-1, "invalid parseStrategy: " + parseStrategy);}itemEntity.setParseStrategy(paramItem.getParseStrategy());// 当参数属性为2-Header 3-URL参数 4-Cookie时,参数名称必填if (Arrays.asList(PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) {// 参数名称String fieldName = paramItem.getFieldName();if (StringUtil.isBlank(fieldName)) {return Result.ofFail(-1, "fieldName can't be null or empty");}itemEntity.setFieldName(paramItem.getFieldName());}String pattern = paramItem.getPattern();// 如果匹配串不为空,验证匹配模式if (StringUtil.isNotEmpty(pattern)) {itemEntity.setPattern(pattern);Integer matchStrategy = paramItem.getMatchStrategy();if (!Arrays.asList(PARAM_MATCH_STRATEGY_EXACT, PARAM_MATCH_STRATEGY_CONTAINS, PARAM_MATCH_STRATEGY_REGEX).contains(matchStrategy)) {return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy);}itemEntity.setMatchStrategy(matchStrategy);}} else {entity.setParamItem(null);}// 阈值类型 0-线程数 1-QPSInteger grade = reqVo.getGrade();if (grade == null) {return Result.ofFail(-1, "grade can't be null");}if (!Arrays.asList(FLOW_GRADE_THREAD, FLOW_GRADE_QPS).contains(grade)) {return Result.ofFail(-1, "invalid grade: " + grade);}entity.setGrade(grade);// QPS阈值Double count = reqVo.getCount();if (count == null) {return Result.ofFail(-1, "count can't be null");}if (count < 0) {return Result.ofFail(-1, "count should be at lease zero");}entity.setCount(count);// 间隔Long interval = reqVo.getInterval();if (interval == null) {return Result.ofFail(-1, "interval can't be null");}if (interval <= 0) {return Result.ofFail(-1, "interval should be greater than zero");}entity.setInterval(interval);// 间隔单位Integer intervalUnit = reqVo.getIntervalUnit();if (intervalUnit == null) {return Result.ofFail(-1, "intervalUnit can't be null");}if (!Arrays.asList(INTERVAL_UNIT_SECOND, INTERVAL_UNIT_MINUTE, INTERVAL_UNIT_HOUR, INTERVAL_UNIT_DAY).contains(intervalUnit)) {return Result.ofFail(-1, "Invalid intervalUnit: " + intervalUnit);}entity.setIntervalUnit(intervalUnit);// 流控方式 0-快速失败 2-匀速排队Integer controlBehavior = reqVo.getControlBehavior();if (controlBehavior == null) {return Result.ofFail(-1, "controlBehavior can't be null");}if (!Arrays.asList(CONTROL_BEHAVIOR_DEFAULT, CONTROL_BEHAVIOR_RATE_LIMITER).contains(controlBehavior)) {return Result.ofFail(-1, "invalid controlBehavior: " + controlBehavior);}entity.setControlBehavior(controlBehavior);if (CONTROL_BEHAVIOR_DEFAULT == controlBehavior) {// 0-快速失败, 则Burst size必填Integer burst = reqVo.getBurst();if (burst == null) {return Result.ofFail(-1, "burst can't be null");}if (burst < 0) {return Result.ofFail(-1, "invalid burst: " + burst);}entity.setBurst(burst);} else if (CONTROL_BEHAVIOR_RATE_LIMITER == controlBehavior) {// 2-匀速排队, 则超时时间必填Integer maxQueueingTimeoutMs = reqVo.getMaxQueueingTimeoutMs();if (maxQueueingTimeoutMs == null) {return Result.ofFail(-1, "maxQueueingTimeoutMs can't be null");}if (maxQueueingTimeoutMs < 0) {return Result.ofFail(-1, "invalid maxQueueingTimeoutMs: " + maxQueueingTimeoutMs);}entity.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs);}Date date = new Date();entity.setGmtModified(date);try {entity = repository.save(entity);publishRules(entity.getApp());} catch (Throwable throwable) {logger.error("update gateway flow rule error:", throwable);return Result.ofThrowable(-1, throwable);}//        if (!publishRules(app, entity.getIp(), entity.getPort())) {
//            logger.warn("publish gateway flow rules fail after update");
//        }return Result.ofSuccess(entity);}@PostMapping("/delete.json")@AuthAction(AuthService.PrivilegeType.DELETE_RULE)public Result<Long> deleteFlowRule(Long id) {if (id == null) {return Result.ofFail(-1, "id can't be null");}GatewayFlowRuleEntity oldEntity = repository.findById(id);if (oldEntity == null) {return Result.ofSuccess(null);}try {repository.delete(id);publishRules(oldEntity.getApp());} catch (Throwable throwable) {logger.error("delete gateway flow rule error:", throwable);return Result.ofThrowable(-1, throwable);}//        if (!publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) {
//            logger.warn("publish gateway flow rules fail after delete");
//        }return Result.ofSuccess(id);}//    private boolean publishRules(String app, String ip, Integer port) {
//        List<GatewayFlowRuleEntity> rules = repository.findAllByMachine(MachineInfo.of(app, ip, port));
//        return sentinelApiClient.modifyGatewayFlowRules(app, ip, port, rules);
//    }
private void publishRules(/*@NonNull*/ String app) throws Exception {List<GatewayFlowRuleEntity> rules = repository.findAllByApp(app);rulePublisher.publish(app, rules);
}
}

十一

启动程序

然后添加流控规则,查询规则都从nacos获取

至此就没问题了

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/23081.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

华为手机录屏在哪里?图文详解帮你找!

随着科技的进步&#xff0c;智能手机已成为我们日常生活中不可或缺的工具。其中&#xff0c;华为手机凭借其卓越的性能和用户体验&#xff0c;在全球范围内赢得了广泛的赞誉。在众多功能中&#xff0c;录屏功能尤为实用&#xff0c;无论是制作教程、记录游戏精彩瞬间&#xff0…

压敏电阻器是在规定温度下,当电压超过某一临界值时电导随电压的升高而急速增大的一种电阻器

压敏电阻器是在规定温度下,当电压超过某一临界值时电导随电压的升高而急速增大的一种电阻器。压敏电阻器的伏安特性是非线性的,因此,压敏电阻器亦称为非线性电阻器,非线性来自于压敏电阻器两端的外加电压,其伏安特性如图 9-1所示。从图9-1可以看出,压敏电阻器有对称型和非对称型…

网络运维简介

目录 1.网络运维的定义 2.诞生背景 3.网络运维的重要性 4.优点 5.缺点 6.应用场景 6.1.十个应用场景 6.2.数据中心运维 7.应用实例 8.小结 1.网络运维的定义 网络运维&#xff08;Network Operations&#xff09;是指管理、监控和维护计算机网络以确保其高效、安全和…

Python私教张大鹏 Vue3整合AntDesignVue之文本组件

案例&#xff1a;展示标题 核心代码&#xff1a; <a-typography><a-typography-title>Introduction</a-typography-title> </a-typography>vue3示例&#xff1a; <template><a-typography><a-typography-title>这是一个标题</…

【K8s】专题四(6):Kubernetes 控制器之 Job

以下内容均来自个人笔记并重新梳理&#xff0c;如有错误欢迎指正&#xff01;如果对您有帮助&#xff0c;烦请点赞、关注、转发&#xff01;欢迎扫码关注个人公众号&#xff01; 目录 一、基本介绍 二、工作原理 三、相关特性 四、资源清单&#xff08;示例&#xff09; 五…

电路分析答疑 1

三要素法求解的时候&#xff0c; 电容先求U&#xff0c;再利用求导求I 电感先求I&#xff0c;再利用求导求U 若I的头上没有点点&#xff0c;那就是求有效值 叠加定理&#xff0c;不要忘记 若电流值或者电压值已经给出来了&#xff0c;那就说明这一定是直流电。 在画画圈的时候…

数据库(25)——多表关系介绍

在项目开发中&#xff0c;进行数据库表结构设计时&#xff0c;会根据业务需求及业务模块之间的关系&#xff0c;分析并设计表结构&#xff0c;各个表之间的结构基本上分为三种&#xff1a;一对多&#xff0c;多对多&#xff0c;一对一。 一对多 例如&#xff0c;一个学校可以有…

Mac修改Mysql8.0密码

转载请标明出处&#xff1a;http://blog.csdn.net/donkor_/article/details/139392605 文章目录 前言修改密码Step1:修改my.conf文件Step2:添加配置skip-grant-tablesStep3:重启mysql服务Step4:进入mysqlStep5:刷新权限Step6:修改密码Step7:再次刷新权限Step8:删除/注释 skip-…

DNS域名

DNS域名 DNS是域名系统的简称 域名和ip地址之间的映射关系 互联网中&#xff0c;ip地址是通信的唯一标识 访问网站&#xff0c;域名&#xff0c;ip地址不好记&#xff0c;域名朗朗上口&#xff0c;好记。 域名解析的目的就是为了实现&#xff0c;访问域名就等于访问ip地址…

【Python】 获取当前日期的Python代码解析与应用

标题&#xff1a;Python中获取当前日期的简单指南 基本原理 在Python中&#xff0c;获取当前日期是一个常见的需求&#xff0c;尤其是在处理日志、数据记录和时间相关的任务时。Python提供了多种方式来获取和处理日期和时间&#xff0c;其中最常用的模块是datetime。datetime…

多客陪玩系统-开源陪玩系统平台源码-支持游戏线上陪玩家政线下预约等多场景应用支持H5+小程序+APP

多客陪玩系统-开源陪玩系统平台源码-支持游戏线上陪玩家政按摩线下预约等多场景应用支持H5小程序APP 软件架构 前端&#xff1a;Uniapp-vue2.0 后端&#xff1a;Thinkphp6 前后端分离 前端支持&#xff1a; H5小程序双端APP&#xff08;安卓苹果&#xff09; 安装教程 【商业…

QT C++ QTableWidget 表格合并 setSpan 简单例子

这里说的合并指的是单元格&#xff0c;不是表头。span的意思是跨度、宽度、范围。 setSpan函数需要设定行、列、行跨几格&#xff0c;列跨几格。 //函数原型如下 void QTableView::setSpan(int row, i nt column, 、 int rowSpanCount,/*行跨过的格数*/ int columnSpanCount…

【算法无用系列】电影推荐——余弦相似度计算用户相似度原理

【算法无用系列】通过余弦相似度计算电影、用户相似度 话不多说&#xff0c;本文通过电影推荐系统中&#xff0c;基于余弦相似度算法计算出用户相似和电影相似原理。希望可以帮助一些代码不懂的同学一些思路。 记录用户电影评分数据 一般情况来说&#xff0c;会根据用户的行为…

什么是数字化转型?

作者&#xff1a; 峡山老曹 数字神化 ”企业如何实现数字化转型“是摆在现代企业面前一个无法回避的问题&#xff0c;数字化转型的重要性不容忽视&#xff0c;它不仅是企业适应数字化时代的必然要求&#xff0c;更是提升竞争力、实现可持续发展的关键。随着科技的飞速发展和市场…

八、C语言:操作符详解

一、移位操作符 1.1左移操作 左边丢弃&#xff0c;右边补0 1.2右移操作 算数右移&#xff1a;右边丢弃&#xff0c;左边补原符号位 逻辑右移&#xff1a;右边丢弃&#xff0c;左边补0 int main() {int a -1;int b a >> 1;printf("b%d\n",b);return 0; } 原码…

【Linux进程篇】Linux进程管理应用——虚假的shell脚本

W...Y的主页 &#x1f60a; 代码仓库分享&#x1f495; 前言&#xff1a;我们已经了解了进程的工作原理&#xff0c;并且学习了进程创建、进程终止、进程等待以及进程程序替换。为了更好的巩固这些知识&#xff0c;我们可以创建一个简易的shell命令行。 目录 做一个简易的s…

GAT1399协议分析(六)--校时

一、官方消息定义 DeviceIDType &#xff1a;GA/T1400.1,采集设备、 卡口点位、 采集系统、分析系统、视图库、应用平台等设备编码规则 TimeCorrectModeType&#xff1a; dateTime时间格式&#xff1a; TimeZone&#xff1a;时区&#xff0c;GAT1400里面没有找到具体内容&…

卧式搅拌机:一键自动称重轻松搞定

在现代化工业生产中&#xff0c;G效、精准的设备是提高生产效率、降低生产成本。近年来&#xff0c;卧式搅拌机一键自动称重包装机的出现&#xff0c;无疑为众多行业带来了变革。这种集搅拌、称重、包装于一体的智能化设备&#xff0c;以其G效、便捷、精准的特点&#xff0c;迅…

六轴机器手臂运动控制——直流伺服反馈系统设计(比赛项目计划书+设计总结+硬件+源代码+上位机等)

TW的硬件一直很强&#xff0c;这是难得的硬件创新比赛的优秀作品&#xff0c;资料非常完整理。 硬件设计&#xff0c;源码&#xff0c;项目计划书&#xff0c;甚至包含了事后的复盘总结文档。 是不可多得的好资料。 项目系统框架图 1. 硬件系统框架图 (请以方块图形式呈现) …

idea的代码没有提交到仓库怎么撤回到本地?

代码已经提交到变更列表但是还没有push推送到仓库上&#xff0c;可以用这个方法 点击日志-右键要撤回的记录-选择撤销提交 撤销的又回到本地变更 当然你只能撤销自己提交的&#xff0c;别人的你撤销不了