sentinel整合nacos配置中心持久化

在网上找了很多的资料,发现sentinel整合nacos持久化的博文和视频大多数都只有改造限流部分的教程,并且都需要修改前端,略显麻烦,至于剩下的熔断、热点流控、授权的更是没有相关的改造教程,最后在知乎的看到一篇文章后让我大受启发

在这里插入图片描述
这位前辈讲到sentinel原来是把配置保存到内存的,我们只需要找出这行保存到内存的代码,把它改为发布到nacos就可以了,这样做改动非常的小,而且不用改前端,是个非常聪明的思路。

下面是我改造的过程,完全不需要改前端:

注释掉nacos依赖的test作用域
在这里插入图片描述

把test目录下nacos文件夹复制一份到java目录下
在这里插入图片描述

改造NacosConfig 类

/** Copyright 1999-2018 Alibaba Group Holding Ltd.** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**      http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/
package com.alibaba.csp.sentinel.dashboard.rule.nacos;import java.util.List;
import java.util.Properties;import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.AuthorityRuleEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.DegradeRuleEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.ParamFlowRuleEntity;
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;import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** @author Eric Zhao* @since 1.4.0*/
@Configuration
public class NacosConfig {// 动态配置nacos地址,用户名,密码@Value("${sentinel.nacos.serverAddr}")private String serverAddr;@Value("${sentinel.nacos.username}")private String username;@Value("${sentinel.nacos.password}")private String password;/*** 加入要改造方法所需实体的编解码器* @return*/// 流控@Beanpublic Converter<List<FlowRuleEntity>, String> flowRuleEntityEncoder() {return JSON::toJSONString;}@Beanpublic Converter<String, List<FlowRuleEntity>> flowRuleEntityDecoder() {return s -> JSON.parseArray(s, FlowRuleEntity.class);}// 熔断@Beanpublic Converter<List<DegradeRuleEntity>, String> degradeRuleEntityEncoder() {return JSON::toJSONString;}@Beanpublic Converter<String, List<DegradeRuleEntity>> degradeRuleEntityDecoder() {return s -> JSON.parseArray(s, DegradeRuleEntity.class);}// 授权@Beanpublic Converter<List<AuthorityRuleEntity>, String> authorityRuleEntityEncoder() {return JSON::toJSONString;}@Beanpublic Converter<String, List<AuthorityRuleEntity>> authorityRuleEntityDecoder() {return s -> JSON.parseArray(s, AuthorityRuleEntity.class);}// 热点流控@Beanpublic Converter<List<ParamFlowRuleEntity>, String> paramFlowRuleEntityEncoder() {return JSON::toJSONString;}@Beanpublic Converter<String, List<ParamFlowRuleEntity>> paramFlowRuleEntityDecoder() {return s -> JSON.parseArray(s, ParamFlowRuleEntity.class);}@Beanpublic ConfigService nacosConfigService() throws Exception {Properties properties = new Properties();properties.put("serverAddr", serverAddr);properties.put("username", username);properties.put("password", password);return ConfigFactory.createConfigService(properties);
//        return ConfigFactory.createConfigService("localhost");}
}

定义发布到配置中心的配置名后缀

/** Copyright 1999-2018 Alibaba Group Holding Ltd.** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**      http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/
package com.alibaba.csp.sentinel.dashboard.rule.nacos;/*** @author Eric Zhao* @since 1.4.0*/
public final class NacosConfigUtil {public static final String GROUP_ID = "SENTINEL_GROUP";// 定义发布到配置中心的配置名后缀public static final String FLOW_DATA_ID_POSTFIX = "-flow-rules";public static final String DEGRADE_DATA_ID_POSTFIX = "-degrade-rules";public static final String PARAM_FLOW_DATA_ID_POSTFIX = "-param-rules";public static final String AUTHORITY_DATA_ID_POSTFIX = "-authority-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() {}}

配置文件中加入需要自定义的配置

#spring settings
server.servlet.encoding.force=true
server.servlet.encoding.charset=UTF-8
server.servlet.encoding.enabled=true#cookie name setting
server.servlet.session.cookie.name=sentinel_dashboard_cookie#logging settings
logging.level.org.springframework.web=INFO
logging.file.name=${user.home}/logs/csp/sentinel-dashboard.log
logging.pattern.file= %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
#logging.pattern.console= %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n#auth settings
auth.filter.exclude-urls=/,/auth/login,/auth/logout,/registry/machine,/version
auth.filter.exclude-url-suffixes=htm,html,js,css,map,ico,ttf,woff,png
# If auth.enabled=false, Sentinel console disable login
auth.username=sentinel
auth.password=sentinel# Inject the dashboard version. It's required to enable
# filtering in pom.xml for this resource file.
sentinel.dashboard.version=@project.version@sentinel.nacos.serverAddr = 127.0.0.1:8848
sentinel.nacos.username = nacos
sentinel.nacos.password = nacos
sentinel.nacos.groupId = SENTINEL_GROUP# custom dataId postfix
sentinel.custom.FLOW_DATA_ID_POSTFIX =
sentinel.custom.DEGRADE_DATA_ID_POSTFIX =
sentinel.custom.AUTHORITY_DATA_ID_POSTFIX =
sentinel.custom.PARAM_FLOW_DATA_ID_POSTFIX =

FlowRuleNacosProvider 类改造

package com.alibaba.csp.sentinel.dashboard.rule.nacos;import java.util.ArrayList;
import java.util.List;
import java.util.Objects;import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.nacos.api.config.ConfigService;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;/*** @author Eric Zhao* @since 1.4.0*/
@Component("flowRuleNacosProvider")
public class FlowRuleNacosProvider implements DynamicRuleProvider<List<FlowRuleEntity>> {@Autowiredprivate ConfigService configService;@Autowiredprivate Converter<String, List<FlowRuleEntity>> converter;// 增加的代码@Value("${sentinel.nacos.groupId}")private String groupId;// 增加的代码@Value("${sentinel.custom.FLOW_DATA_ID_POSTFIX}")private String dataIdPostfix;@Overridepublic List<FlowRuleEntity> getRules(String appName) throws Exception {// 增加的代码 用于判断是否自定义dataid后缀if (dataIdPostfix.isEmpty()){dataIdPostfix = NacosConfigUtil.FLOW_DATA_ID_POSTFIX;}String rules = configService.getConfig(appName + dataIdPostfix,groupId, 3000);if (StringUtil.isEmpty(rules)) {return new ArrayList<>();}return converter.convert(rules);}
}

FlowRuleNacosPublisher 类的改造

package com.alibaba.csp.sentinel.dashboard.rule.nacos;import java.util.List;import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.nacos.api.config.ConfigService;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;/*** @author Eric Zhao* @since 1.4.0*/
@Component("flowRuleNacosPublisher")
public class FlowRuleNacosPublisher implements DynamicRulePublisher<List<FlowRuleEntity>> {@Autowiredprivate ConfigService configService;@Autowiredprivate Converter<List<FlowRuleEntity>, String> converter;// 增加的代码@Value("${sentinel.nacos.groupId}")private String groupId;// 增加的代码@Value("${sentinel.custom.FLOW_DATA_ID_POSTFIX}")private String dataIdPostfix;@Overridepublic void publish(String app, List<FlowRuleEntity> rules) throws Exception {// 增加的代码 用于判断是否自定义dataid后缀if (dataIdPostfix.isEmpty()){dataIdPostfix = NacosConfigUtil.FLOW_DATA_ID_POSTFIX;}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));configService.publishConfig(app + dataIdPostfix,groupId, converter.convert(rules));}
}

熔断、授权、热点流控Provider和Publisher的改造与流控的类似,改下对应实体类型、后缀、组件名即可

FlowControllerV1 类的改造

package com.alibaba.csp.sentinel.dashboard.controller;import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;import com.alibaba.csp.sentinel.dashboard.auth.AuthAction;
import com.alibaba.csp.sentinel.dashboard.auth.AuthService.PrivilegeType;
import com.alibaba.csp.sentinel.dashboard.discovery.AppManagement;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.util.StringUtil;import com.alibaba.csp.sentinel.dashboard.client.SentinelApiClient;
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.repository.rule.InMemoryRuleRepositoryAdapter;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.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;/*** Flow rule controller.** @author leyou* @author Eric Zhao*/
@RestController
@RequestMapping(value = "/v1/flow")
public class FlowControllerV1 {private final Logger logger = LoggerFactory.getLogger(FlowControllerV1.class);@Autowiredprivate InMemoryRuleRepositoryAdapter<FlowRuleEntity> repository;@Autowiredprivate AppManagement appManagement;@Autowiredprivate SentinelApiClient sentinelApiClient;// 增加的代码,注入用于发布nacos配置的类@Autowired@Qualifier("flowRuleNacosProvider")private DynamicRuleProvider<List<FlowRuleEntity>> ruleProvider;@Autowired@Qualifier("flowRuleNacosPublisher")private DynamicRulePublisher<List<FlowRuleEntity>> rulePublisher;@GetMapping("/rules")@AuthAction(PrivilegeType.READ_RULE)public Result<List<FlowRuleEntity>> apiQueryMachineRules(@RequestParam String app,@RequestParam String ip,@RequestParam 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");}if (!appManagement.isValidMachineOfApp(app, ip)) {return Result.ofFail(-1, "given ip does not belong to given app");}try {
//            List<FlowRuleEntity> rules = sentinelApiClient.fetchFlowRuleOfMachine(app, ip, port);// 增加的代码,把查询内存改为查询naocos配置中心List<FlowRuleEntity> rules = ruleProvider.getRules(app);if (rules != null && !rules.isEmpty()) {for (FlowRuleEntity entity : rules) {entity.setApp(app);if (entity.getClusterConfig() != null && entity.getClusterConfig().getFlowId() != null) {entity.setId(entity.getClusterConfig().getFlowId());}}}rules = repository.saveAll(rules);return Result.ofSuccess(rules);} catch (Throwable throwable) {logger.error("Error when querying flow rules", throwable);return Result.ofThrowable(-1, throwable);}}...private CompletableFuture<Void> publishRules(String app, String ip, Integer port) throws Exception {List<FlowRuleEntity> rules = repository.findAllByMachine(MachineInfo.of(app, ip, port));// 增加的代码,把新增的规则发布到指定的nacos配置中心rulePublisher.publish(app, rules);// 保留保存到内存的逻辑return sentinelApiClient.setFlowRuleOfMachineAsync(app, ip, port, rules);}
}

DegradeController 类改造

package com.alibaba.csp.sentinel.dashboard.controller;import com.alibaba.csp.sentinel.dashboard.auth.AuthAction;
import com.alibaba.csp.sentinel.dashboard.auth.AuthService.PrivilegeType;
import com.alibaba.csp.sentinel.dashboard.client.SentinelApiClient;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.DegradeRuleEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.discovery.AppManagement;
import com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo;
import com.alibaba.csp.sentinel.dashboard.domain.Result;
import com.alibaba.csp.sentinel.dashboard.repository.rule.RuleRepository;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.circuitbreaker.CircuitBreakerStrategy;
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.Date;
import java.util.List;/*** Controller regarding APIs of degrade rules. Refactored since 1.8.0.** @author Carpenter Lee* @author Eric Zhao*/
@RestController
@RequestMapping("/degrade")
public class DegradeController {private final Logger logger = LoggerFactory.getLogger(DegradeController.class);@Autowiredprivate RuleRepository<DegradeRuleEntity, Long> repository;@Autowiredprivate SentinelApiClient sentinelApiClient;// 增加的代码,注入用于发布nacos配置的类@Autowired@Qualifier("degradeRuleNacosProvider")private DynamicRuleProvider<List<DegradeRuleEntity>> ruleProvider;@Autowired@Qualifier("degradeRuleNacosPublisher")private DynamicRulePublisher<List<DegradeRuleEntity>> rulePublisher;@Autowiredprivate AppManagement appManagement;@GetMapping("/rules.json")@AuthAction(PrivilegeType.READ_RULE)public Result<List<DegradeRuleEntity>> apiQueryMachineRules(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");}if (!appManagement.isValidMachineOfApp(app, ip)) {return Result.ofFail(-1, "given ip does not belong to given app");}try {// 增加的代码 查询nacos配置中心List<DegradeRuleEntity> rules = ruleProvider.getRules(app);if (rules != null && !rules.isEmpty()) {for (DegradeRuleEntity entity : rules) {entity.setApp(app);}}
//            List<DegradeRuleEntity> rules = sentinelApiClient.fetchDegradeRuleOfMachine(app, ip, port);rules = repository.saveAll(rules);return Result.ofSuccess(rules);} catch (Throwable throwable) {logger.error("queryApps error:", throwable);return Result.ofThrowable(-1, throwable);}}....private boolean publishRules(String app, String ip, Integer port) throws Exception {List<DegradeRuleEntity> rules = repository.findAllByMachine(MachineInfo.of(app, ip, port));// 增加的代码 保存到nacosrulePublisher.publish(app, rules);return sentinelApiClient.setDegradeRuleOfMachine(app, ip, port, rules);}
}

AuthorityRuleController 类的改造

import java.util.Date;
import java.util.List;import com.alibaba.csp.sentinel.dashboard.auth.AuthAction;
import com.alibaba.csp.sentinel.dashboard.client.SentinelApiClient;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.discovery.AppManagement;
import com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo;
import com.alibaba.csp.sentinel.dashboard.auth.AuthService.PrivilegeType;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.util.StringUtil;import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.AuthorityRuleEntity;
import com.alibaba.csp.sentinel.dashboard.domain.Result;
import com.alibaba.csp.sentinel.dashboard.repository.rule.RuleRepository;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.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;/*** @author Eric Zhao* @since 0.2.1*/
@RestController
@RequestMapping(value = "/authority")
public class AuthorityRuleController {private final Logger logger = LoggerFactory.getLogger(AuthorityRuleController.class);@Autowiredprivate SentinelApiClient sentinelApiClient;@Autowiredprivate RuleRepository<AuthorityRuleEntity, Long> repository;@Autowiredprivate AppManagement appManagement;// 增加的代码,注入用于发布nacos配置的类@Autowired@Qualifier("authorityRuleNacosProvider")private DynamicRuleProvider<List<AuthorityRuleEntity>> ruleProvider;@Autowired@Qualifier("authorityRuleNacosPublisher")private DynamicRulePublisher<List<AuthorityRuleEntity>> rulePublisher;@GetMapping("/rules")@AuthAction(PrivilegeType.READ_RULE)public Result<List<AuthorityRuleEntity>> apiQueryAllRulesForMachine(@RequestParam String app,@RequestParam String ip,@RequestParam Integer port) {if (StringUtil.isEmpty(app)) {return Result.ofFail(-1, "app cannot be null or empty");}if (StringUtil.isEmpty(ip)) {return Result.ofFail(-1, "ip cannot be null or empty");}if (port == null || port <= 0) {return Result.ofFail(-1, "Invalid parameter: port");}if (!appManagement.isValidMachineOfApp(app, ip)) {return Result.ofFail(-1, "given ip does not belong to given app");}try {
//            List<AuthorityRuleEntity> rules = sentinelApiClient.fetchAuthorityRulesOfMachine(app, ip, port);// 增加的代码 查询nacos配置中心List<AuthorityRuleEntity> rules = ruleProvider.getRules(app);if (rules != null && !rules.isEmpty()) {for (AuthorityRuleEntity entity : rules) {entity.setApp(app);}}rules = repository.saveAll(rules);return Result.ofSuccess(rules);} catch (Throwable throwable) {logger.error("Error when querying authority rules", throwable);return Result.ofFail(-1, throwable.getMessage());}}...private boolean publishRules(String app, String ip, Integer port) throws Exception {List<AuthorityRuleEntity> rules = repository.findAllByMachine(MachineInfo.of(app, ip, port));// 增加的代码 保存到nacosrulePublisher.publish(app, rules);return sentinelApiClient.setAuthorityRuleOfMachine(app, ip, port, rules);}
}

ParamFlowRuleController 类的改造,Provider查询类返回类型不同,对应的Provider类也要做相应的修改

package com.alibaba.csp.sentinel.dashboard.controller;import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;import com.alibaba.csp.sentinel.dashboard.auth.AuthAction;
import com.alibaba.csp.sentinel.dashboard.client.CommandNotFoundException;
import com.alibaba.csp.sentinel.dashboard.client.SentinelApiClient;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.discovery.AppManagement;
import com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo;
import com.alibaba.csp.sentinel.dashboard.auth.AuthService;
import com.alibaba.csp.sentinel.dashboard.auth.AuthService.PrivilegeType;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.ParamFlowRuleNacosProvider;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.SentinelVersion;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.ParamFlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.domain.Result;
import com.alibaba.csp.sentinel.dashboard.repository.rule.RuleRepository;
import com.alibaba.csp.sentinel.dashboard.util.VersionUtils;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.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;/*** @author Eric Zhao* @since 0.2.1*/
@RestController
@RequestMapping(value = "/paramFlow")
public class ParamFlowRuleController {private final Logger logger = LoggerFactory.getLogger(ParamFlowRuleController.class);@Autowiredprivate SentinelApiClient sentinelApiClient;@Autowiredprivate AppManagement appManagement;@Autowiredprivate RuleRepository<ParamFlowRuleEntity, Long> repository;// 增加的代码,注入用于发布nacos配置的类// 这个查询返回的类型与其他三个方法有些区别@Autowired@Qualifier("paramFlowRuleNacosProvider")private ParamFlowRuleNacosProvider ruleProvider;@Autowired@Qualifier("paramFlowRuleNacosPublisher")private DynamicRulePublisher<List<ParamFlowRuleEntity>> rulePublisher;private boolean checkIfSupported(String app, String ip, int port) {try {return Optional.ofNullable(appManagement.getDetailApp(app)).flatMap(e -> e.getMachine(ip, port)).flatMap(m -> VersionUtils.parseVersion(m.getVersion()).map(v -> v.greaterOrEqual(version020))).orElse(true);// If error occurred or cannot retrieve machine info, return true.} catch (Exception ex) {return true;}}@GetMapping("/rules")@AuthAction(PrivilegeType.READ_RULE)public Result<List<ParamFlowRuleEntity>> apiQueryAllRulesForMachine(@RequestParam String app,@RequestParam String ip,@RequestParam Integer port) {if (StringUtil.isEmpty(app)) {return Result.ofFail(-1, "app cannot be null or empty");}if (StringUtil.isEmpty(ip)) {return Result.ofFail(-1, "ip cannot be null or empty");}if (port == null || port <= 0) {return Result.ofFail(-1, "Invalid parameter: port");}if (!appManagement.isValidMachineOfApp(app, ip)) {return Result.ofFail(-1, "given ip does not belong to given app");}if (!checkIfSupported(app, ip, port)) {return unsupportedVersion();}try {// 增加的代码 查询nacos配置中心 与其他三个方法有些区别return ruleProvider.getRules(app).thenApply(repository::saveAll).thenApply(Result::ofSuccess).get();
//            return sentinelApiClient.fetchParamFlowRulesOfMachine(app, ip, port)
//                    .thenApply(repository::saveAll)
//                    .thenApply(Result::ofSuccess)
//                    .get();} catch (ExecutionException ex) {logger.error("Error when querying parameter flow rules", ex.getCause());if (isNotSupported(ex.getCause())) {return unsupportedVersion();} else {return Result.ofThrowable(-1, ex.getCause());}} catch (Throwable throwable) {logger.error("Error when querying parameter flow rules", throwable);return Result.ofFail(-1, throwable.getMessage());}}private boolean isNotSupported(Throwable ex) {return ex instanceof CommandNotFoundException;}...private CompletableFuture<Void> publishRules(String app, String ip, Integer port) throws Exception {List<ParamFlowRuleEntity> rules = repository.findAllByMachine(MachineInfo.of(app, ip, port));// 增加的代码 保存到nacosrulePublisher.publish(app, rules);return sentinelApiClient.setParamFlowRuleOfMachine(app, ip, port, rules);}
}

具体的ParamFlowRuleNacosProvider 类

package com.alibaba.csp.sentinel.dashboard.rule.nacos;import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.ParamFlowRuleEntity;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;import java.util.List;
import java.util.concurrent.CompletableFuture;/*** @ClassName: ParamFlowRuleNacosProvider* @Description: TODO* @Author: ChiKin Lau @ SUSE* @Date: 2023/11/8 10:08* @version: 1.0**/
@Component("paramFlowRuleNacosProvider")
public class ParamFlowRuleNacosProvider {@Autowiredprivate ConfigService configService;@Autowiredprivate Converter<String, List<ParamFlowRuleEntity>> converter;// 增加的代码@Value("${sentinel.nacos.groupId}")private String groupId;@Value("${sentinel.custom.PARAM_FLOW_DATA_ID_POSTFIX}")private String dataIdPostfix;public CompletableFuture<List<ParamFlowRuleEntity>> getRules(String appName) throws Exception {// 增加的代码 用于判断是否自定义dataid后缀if (dataIdPostfix.isEmpty()){dataIdPostfix = NacosConfigUtil.PARAM_FLOW_DATA_ID_POSTFIX;}String rules = configService.getConfig(appName + dataIdPostfix,groupId, 3000);
//        if (StringUtil.isEmpty(rules)) {
//            return new CompletableFuture<>();
//        }// 增加的代码 用于适应不同的返回类型CompletableFuture<String> future = new CompletableFuture<>();future.complete(rules);return future.thenApply(json -> JSON.parseArray(json, ParamFlowRuleEntity.class));}
}

OK,至此所有的改造完成了,使用maven进行打包即可使用,使用这个jar包在页面端的sentinel配可以保存到nacos进行持久化了,包括了流控、熔断、授权和热点限流。
在这里插入图片描述

下面附上

源码的GitHub地址: https://github.com/chikin-lau/sentinel-nacos
jar包及使用说明压缩包:
链接:https://pan.baidu.com/s/1jvcSCQw-YjeT5-nRocQOUA
提取码:8xry
–来自百度网盘超级会员V3的分享

参考文章:
https://zhuanlan.zhihu.com/p/663149010

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

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

相关文章

百科词条可以删除吗?如何删除自己的百度百科?

近日&#xff0c;小马识途营销顾问接到不少客户删除自己百科词条的咨询&#xff0c;有不少人自己并没有去建立百科词条&#xff0c;但是网上已经有了&#xff0c;有的信息不正确&#xff0c;甚至有的信息是负能量的&#xff0c;对当事人自己造成一定的困扰&#xff0c;所以寻求…

PbootCMS 前台RCE漏洞复现

0x01 产品简介 PbootCMS是全新内核且永久开源免费的PHP企业网站开发建设管理系统,是一套高效、简洁、 强悍的可免费商用的PHP CMS源码,能够满足各类企业网站开发建设的需要 0x02 漏洞概述 PbootCMS v<=3.1.6版本中存在模板注入,攻击者可构造特定的链接利用该漏洞,执行…

线程及实现方式

一、线程 线程是一个基本的CPU执行单元&#xff0c;也是程序执行流的最小单位。引入线程之后&#xff0c;不仅是进程之间可以并发&#xff0c;进程内的各线程之间也可以并发&#xff0c;从而进一步提升了系统的并发度&#xff0c;使得一个进程内也可以并发处理各种任务&#x…

【Hive】——安装部署

1 MetaData&#xff08;元数据&#xff09; 2 MetaStore &#xff08;元数据服务&#xff09; 3 MetaStore配置方式 3.1 内嵌模式 3.2 本地模式 3.3 远程模式 4 安装前准备 <!-- 整合hive --><property><name>hadoop.proxyuser.root.hosts</name><v…

Java+Swing: 主界面组件布局 整理9

说明&#xff1a;这篇博客是在上一篇的基础上的&#xff0c;因为上一篇已经将界面的框架搭好了&#xff0c;这篇主要是将里面的组件完善。 分为三个部分&#xff0c;北边的组件、中间的组件、南边的组件 // 放置北边的组件layoutNorth(contentPane);// 放置中间的 Jtablelayou…

Tair(3):Tair入门demo

新建一个maven项目 1 导入依赖 <dependency><groupId>com.taobao.tair</groupId><artifactId>tair-client</artifactId><version>2.3.5</version></dependency><dependency><groupId>com.alibaba</groupId>…

Linux权限(用户角色+文件权限属性)

Linux权限 文章目录 Linux权限一.文件权限1.快速掌握修改权限的方法&#xff08;修改文件权限属性&#xff09;2.对比权限的有无&#xff0c;以及具体的体现3.修改权限的第二套方法&#xff08;修改用户角色&#xff09;4.文件类型&#xff08;Linux下一切皆文件&#xff09; 二…

049:VUE 引入jquery的方法和配置

第049个 查看专栏目录: VUE ------ element UI 专栏目标 在vue和element UI联合技术栈的操控下&#xff0c;本专栏提供行之有效的源代码示例和信息点介绍&#xff0c;做到灵活运用。 &#xff08;1&#xff09;提供vue2的一些基本操作&#xff1a;安装、引用&#xff0c;模板使…

springboot基础(80):redis geospatial的应用

文章目录 前言redis geospatial如何从地图上获取经纬度springboot 的相关方法调用准备redis服务器引用的依赖预设位置的keyGEOADD 添加位置GEORADIUS 获取指定经纬度附件的停车场&#xff08;deprecated&#xff09;GEORADIUS 获取指定成员附件的停车场&#xff08;deprecated&…

文心一言API(高级版)使用

文心一言API高级版使用 一、百度文心一言API(高级版)二、使用步骤1、接口2、请求参数3、请求参数示例4、接口 返回示例 三、 如何获取appKey和uid1、申请appKey:2、获取appKey和uid 四、重要说明 一、百度文心一言API(高级版) 基于百度文心一言语言大模型的智能文本对话AI机器…

归并排序--分治法

代码 #include<iostream> using namespace std;void merge(int arr[], int p, int q, int r, int temp[]) {int i p;int j q 1;int k 0;while (i < q && j < r){if (arr[i] < arr[j]){temp[k] arr[i];}else{temp[k] arr[j];}}while (i < q){t…

智能优化算法应用:基于蚁狮算法3D无线传感器网络(WSN)覆盖优化 - 附代码

智能优化算法应用&#xff1a;基于蚁狮算法3D无线传感器网络(WSN)覆盖优化 - 附代码 文章目录 智能优化算法应用&#xff1a;基于蚁狮算法3D无线传感器网络(WSN)覆盖优化 - 附代码1.无线传感网络节点模型2.覆盖数学模型及分析3.蚁狮算法4.实验参数设定5.算法结果6.参考文献7.MA…

ptmalloc:从内存虚拟化说起

前言 本文并不局限于ptmalloc的原理&#xff0c;而是从linux的内存虚拟化和系统调用原理出发&#xff0c;结合各种语言实现&#xff0c;讲明内存分配方面的trade off&#xff0c;力图事无巨细&#xff0c;追根究底。本文内容包括但不限于&#xff1a;NIO原理、0拷贝原理、内存…

leetcode:643. 子数组最大平均数 I(滑动窗口)

一、题目 链接&#xff1a;643. 子数组最大平均数 I - 力扣&#xff08;LeetCode&#xff09; 函数原型&#xff1a; double findMaxAverage(int* nums, int numsSize, int k) 二、思路 滑动窗口&#xff1a; 先计算数组前k个元素总和&#xff0c;作为第一个窗口&#xff0c;默…

vlog如何降低重复率

大家好&#xff0c;今天来聊聊vlog如何降低重复率&#xff0c;希望能给大家提供一点参考。 以下是针对论文重复率高的情况&#xff0c;提供一些修改建议和技巧&#xff1a; vlog如何降低重复率 Vlog作为一种流行的视频日志形式&#xff0c;常常被人们用于记录日常生活、分享经…

pta模拟题——7-34 刮刮彩票

“刮刮彩票”是一款网络游戏里面的一个小游戏。如图所示&#xff1a; 每次游戏玩家会拿到一张彩票&#xff0c;上面会有 9 个数字&#xff0c;分别为数字 1 到数字 9&#xff0c;数字各不重复&#xff0c;并以 33 的“九宫格”形式排布在彩票上。 在游戏开始时能看见一个位置上…

Lambda表达式规则,用法

Lambda表达式是JDK8新增的一种语法格式 1.作用 简化匿名内部类的代码写法 Lambad用法前提&#xff1a;只能简化函数式接口&#xff08;一般加有Funcationallnterface&#xff09;&#xff08;有且仅有一个抽象方法&#xff09;的匿名内部类 匿名内部类&#xff1a;(本质是对…

2023年终总结-轻舟已过万重山

自我介绍 高考大省的读书人 白&#xff0c;陇西布衣&#xff0c;流落楚、汉。-与韩荆州书 我来自孔孟故里山东济宁&#xff0c;也许是小学时的某一天&#xff0c;我第一次接触到了电脑&#xff0c;从此对它产生了强烈的兴趣&#xff0c;高中我有一个愿望&#xff1a;成为一名计…

设计模式再探——装饰模式

目录 一、背景介绍二、思路&方案三、过程1.装饰模式简介2.装饰模式的类图3.装饰模式代码4.装饰模式&#xff0c;职责父类拆分的奥义5.装饰模式&#xff0c;部件抽象类的无中生有 四、总结五、升华 一、背景介绍 最近公司在做架构模型的时候&#xff0c;涉及到装饰模式的研…

html网页设计 01marquee标签广告滚动(1)

<!DOCTYPE html> <html><head><meta charset"utf-8"><title></title></head><body><!-- scrollamount:数字越大&#xff0c;滚动越快direction:滚动方向滚动的类型behaior"slide",文字滚动到边界后就会…