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.rhkb.cn/news/346301.html

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

相关文章

Vue3+vite部署nginx的二级目录,使用hash模式

修改router访问路径 import { createRouter, createWebHashHistory } from vue-routerconst router createRouter({history: createWebHashHistory (/mall4pc-bbc/),routes: [XXX,] })配置package.json文件 "build:testTwo": "vite build --mode testing --ba…

计算机网络学习记录 网络层 Day4(下)

计算机网络学习记录 网络层 Day4 &#xff08;下&#xff09; 你好,我是Qiuner. 为记录自己编程学习过程和帮助别人少走弯路而写博客 这是我的 github https://github.com/Qiuner ⭐️ ​ gitee https://gitee.com/Qiuner &#x1f339; 如果本篇文章帮到了你 不妨点个赞吧~ 我…

hadoop未授权访问命令执行漏洞复现-vulfocus

1 介绍 Hadoop YARN&#xff08;Yet Another Resource Negotiator&#xff09;的ResourceManager是集群资源管理的核心组件&#xff0c;负责分配和管理集群资源以及调度作业。如果ResourceManager出现未授权访问漏洞&#xff0c;可能允许未经认证的用户访问或操作集群资源&…

在 Android App 里使用 C 代码 - NDK

原生开发套件 (NDK) 是一套工具&#xff0c;使能够在 Android 应用中使用 C 和 C 代码&#xff0c;并提供众多平台库&#xff0c;可使用这些平台库管理原生 activity 和访问实体设备组件&#xff0c;例如传感器和触控输入。 NDK 可能不适合大多数 Android 编程初学者&#xff…

2022 hnust 湖科大 javaweb课设 数据库课设 报告+源代码+流程图文件+课设指导书+附赠数据库课堂实验指导书

2022 hnust 湖科大 javaweb课设 数据库课设 报告源代码流程图文件课设指导书附赠数据库课堂实验指导书 描述 湖南科技大学大二下学期先后开展java web和数据库课程设计&#xff0c;两个课设项目可以通用&#xff0c;老师一般会允许自拟选题&#xff0c;所以在此统一打包&…

Sentinel不使用控制台基于注解限流,热点参数限流

目录 一、maven依赖 二、控制台 三、基于注解限流 四、热点参数限流 五、使用JMeter验证 一、maven依赖 需要注意&#xff0c;使用的版本需要和你的SpringBoot版本匹配&#xff01;&#xff01; Spring-Cloud直接添加如下依赖即可&#xff0c;baba已经帮你指定好版本了。…

tomcat10部署踩坑记录-公网IP和服务器系统IP搞混

1. 服务器基本条件 使用的阿里云服务器&#xff0c;镜像系统是Ubuntu16.04java version “17.0.11” 2024-04-16 LTS装的是tomcat10.1.24阿里云服务器安全组放行了&#xff1a;8080端口 服务器防火墙关闭&#xff1a; 监听情况和下图一样&#xff1a; tomcat正常启动&#xff…

C# 集成 C++ 的方法和实践 - P/Invoke(平台调用)- 1

环境&#xff1a; 1 P/Invoke&#xff08;平台调用&#xff09;&#xff1a; C#可以通过P/Invoke调用C编写的DLL中的函数。 1.1 适用范围&#xff1a; P/Invoke 是一种在 C# 程序中调用非托管代码&#xff08;如 C 动态链接库&#xff09;的方式。这种方法适用于函数调用相对…

国外媒体软文发稿-引时代潮流-助力跨国企业蓬勃发展

大舍传媒&#xff1a;开疆拓土&#xff0c;引领传媒新潮流 随着全球经济的一体化和信息技术的高速发展&#xff0c;跨国企业在国际市场上的竞争越来越激烈。这也给跨国企业带来了巨大的机遇和挑战。在这个时代背景下&#xff0c;大舍传媒凭借其独特的优势和创新的服务模式&…

pdf的压缩该怎么做?快速在线压缩pdf的方法

pdf文件是现在很常用的一种文件格式&#xff0c;有很多的文件内容都可以通过这种格式来展示内容&#xff0c;比如一些通知文件、设计图、个人信息等等&#xff0c;文件的内容越多就会越大&#xff0c;在使用的时候经常会受到一定的限制。那么有什么方法能够快速的将pdf文件变小…

【C++】C++ QT实现Huffman编码器与解码器(源码+课程论文+文件)【独一无二】

&#x1f449;博__主&#x1f448;&#xff1a;米码收割机 &#x1f449;技__能&#x1f448;&#xff1a;C/Python语言 &#x1f449;公众号&#x1f448;&#xff1a;测试开发自动化【获取源码商业合作】 &#x1f449;荣__誉&#x1f448;&#xff1a;阿里云博客专家博主、5…

SVNCloud 与 Navicat和IDEA的连接

文章目录 SVNCloud 配置Navicat访问云端数据库与IDEA Java jdbc 的连接 SVNCloud 配置 访问网址&#xff1a;SVN注册账号&#xff0c;进入mysql区域&#xff1a; 数据库管理->创建数据库&#xff0c;输入数据库名称和密码&#xff0c;注意&#xff0c;这里的数据库名称实际…

Facebook企业户 | Facebook公共主页经营

Facebook作为社交媒体巨头&#xff0c;拥有庞大的用户基数&#xff0c;因此&#xff0c;有效经营公共主页是获取持续流量、提升客户信任度和粘性、促进产品或服务销售与转化的关键。要优化Facebook主页&#xff0c;关注以下几点&#xff1a; 1、参与度是关键指标&#xff1a;因…

如何一键拷贝PPT中的所有文字?

有时我们可能需要引用PPT的文字&#xff0c;但一个幻灯片一个幻灯片拷贝很是麻烦&#xff0c;我们想一键拷贝PPT中所有幻灯片中的内容&#xff08;最近我就遇到了这个需求&#xff09;。今天就来讲讲这个一键拷贝的技巧。因为大家可能会遇到同样的问题&#xff0c;所以在此记录…

【MySQL】(基础篇五) —— 排序检索数据

排序检索数据 本章将讲授如何使用SELECT语句的ORDER BY子句&#xff0c;根据需要排序检索出的数据。 排序数据 还是使用上一节中的例子,查询employees表中的last_name字段 SELECT last_name FROM employees;输出结果&#xff1a; 发现其输出并没有特定的顺序。其实&#xf…

Django ListView 列表视图类

ListView是Django的通用视图之一&#xff0c;它用于显示一个对象列表。这个视图将所有的对象作为一个上下文变量传递给模板。 1&#xff0c;创建应用 python manage.py startapp app3 2&#xff0c;注册应用 Test/Test/settings.py Test/Test/urls.py 3&#xff0c;添加模型 …

策略模式的理解和运用

在之前的小游戏项目中&#xff0c;处理websocket长连接请求的时候&#xff0c;需要根据传递数据包的不同类型&#xff0c;进行不同的处理。为了实现这个场景&#xff0c;比较简单的方法就是使用if-else或者switch-case语句&#xff0c;根据条件进行判断。但是这导致了项目代码复…

C语言基础——函数

ʕ • ᴥ • ʔ づ♡ど &#x1f389; 欢迎点赞支持&#x1f389; 个人主页&#xff1a;励志不掉头发的内向程序员&#xff1b; 专栏主页&#xff1a;C语言基础&#xff1b; 文章目录 前言 一、函数的概念 二、库函数 2.1 库函数和头文件 2.2 库函数的使用/…

【react】react项目支持鼠标拖拽的边框改变元素宽度的组件

目录 安装使用方法示例Props 属性方法示例代码调整兄弟div的宽度 re-resizable github地址 安装 $ npm install --save re-resizable这将安装re-resizable库并将其保存为项目的依赖项。 使用方法 re-resizable 提供了一个 <Resizable> 组件&#xff0c;它可以包裹任何…

Java——方法详细介绍

一、方法调用机制 1、方法调用机制详细介绍 下面对方法调用在内存中的情况进行分析&#xff0c;以下面的代码为例&#xff1a; public class Test {public static void main(String[] args) {Person person new Person();person.name "张三";person.age 18;int…