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,一经查实,立即删除!

相关文章

介绍下CIDR(Classless Inter-Domain Routing)无类别域间路由

最近在搞DELL EMC XtremIO的重新初始化&#xff0c;在Stortage controller和XMS的xinstall配置的时候&#xff0c;需要配置用到CIDR&#xff0c;就是classless inter-domian routing&#xff0c;总结了一下&#xff0c;其实很多对网络设备的地方都用得到&#xff0c;以前还不知…

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

随着科技的进步&#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;是指管理、监控和维护计算机网络以确保其高效、安全和…

2024最新华为OD算法题目

在一个机房中,服务器的位置标识在 n*m 的整数矩阵网格中,1表示单元格上有服务器,0 表示没有。如果两台服务器位于同一行或者同一列中紧邻的位置,则认为它们之间可以组成一个局域网。请你统计机房中最大的局域网包含的服务器个数。 输入描述 第一行输入两个正整数,n和m,…

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

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

HTTP请求过程

HTTP&#xff08;超文本传输协议&#xff09;请求过程是客户端&#xff08;通常是浏览器&#xff09;与服务器之间通信的方式&#xff0c;用于从服务器请求资源&#xff08;如网页、图片、视频等&#xff09;。以下是HTTP请求的基本步骤&#xff1a; 建立TCP连接&#xff1a; 如…

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

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

C语言经典习题20

一编写一个函数用于计算高于平均分的人数 编写一个函数int fun(float s[],int n)&#xff0c;用于计算高于平均分的人数&#xff0c;并作为函数值返回&#xff0c;其中数组s中存放n位学生的成绩。再编写一个主函数&#xff0c;从键盘输入一批分数&#xff08;用-1来结束输入&a…

电路分析答疑 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; 安装教程 【商业…

学习VUE3——组件(一)

组件注册 分为全局注册和局部注册两种。 全局注册&#xff1a; 在main.js或main.ts中&#xff0c;使用 Vue 应用实例的 .component() 方法&#xff0c;让组件在当前 Vue 应用中全局可用。 import { createApp } from vue import MyComponent from ./App.vueconst app crea…

11、“十四五”大数据产业发展规划

数据是新时代重要的生产要素, 是国家基础性战略资源。 大数据是数据的集合, 以容量大、 类型多、 速度快、 精度准、 价值高为主要特征, 是推动经济转型发展的新动力,是提升政府治理能力的新途径, 是重塑国家竞争优势的新机遇。 大数据产业是以数据生成、 采集、 存储、 加…

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;更是提升竞争力、实现可持续发展的关键。随着科技的飞速发展和市场…