有两种方式可以实现:
  • Springboot客户端相应配置(推荐)
  • 修改sentinel-dashboard的源码

一、Springboot客户端做相应配置(推荐

1、添加依赖

        <dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-datasource-nacos</artifactId></dependency>

这里面已经实现了从nacos读取配置的方法,我们只需实现写入的方法即可

2、新建NacosWritableDataSource

利用 nacos 的 com.alibaba.nacos.api.config.ConfigService#publishConfig(java.lang.String, java.lang.String, java.lang.String) 方法,既会修改持久化文件,也会同步到对应的微服务

@Slf4j
public class NacosWritableDataSource<T> implements WritableDataSource<T> {private NacosDataSourceProperties nacosDataSourceProperties;private ConfigService configService;private final Converter<T, String> configEncoder;private final Lock lock = new ReentrantLock(true);public NacosWritableDataSource(NacosDataSourceProperties nacosDataSourceProperties,Converter<T, String> configEncoder) {this.nacosDataSourceProperties = nacosDataSourceProperties;this.configEncoder = configEncoder;// 初始化 nacos configServiceinitConfigService();}private void initConfigService() {try {this.configService = NacosFactory.createConfigService(buildProperties(nacosDataSourceProperties));} catch (NacosException e) {log.error("init nacos configService error", e);}}private Properties buildProperties(NacosDataSourceProperties nacosDataSourceProperties) {Properties properties = new Properties();if (StringUtils.hasLength(nacosDataSourceProperties.getServerAddr())) {properties.setProperty(PropertyKeyConst.SERVER_ADDR, nacosDataSourceProperties.getServerAddr());} else {properties.setProperty(PropertyKeyConst.ACCESS_KEY, nacosDataSourceProperties.getAccessKey());properties.setProperty(PropertyKeyConst.SECRET_KEY, nacosDataSourceProperties.getSecretKey());properties.setProperty(PropertyKeyConst.ENDPOINT, nacosDataSourceProperties.getEndpoint());}if (StringUtils.hasLength(nacosDataSourceProperties.getNamespace())) {properties.setProperty(PropertyKeyConst.NAMESPACE, nacosDataSourceProperties.getNamespace());}if (StringUtils.hasLength(nacosDataSourceProperties.getUsername())) {properties.setProperty(PropertyKeyConst.USERNAME, nacosDataSourceProperties.getUsername());}if (StringUtils.hasLength(nacosDataSourceProperties.getPassword())) {properties.setProperty(PropertyKeyConst.PASSWORD, nacosDataSourceProperties.getPassword());}return properties;}@Overridepublic void write(T value) throws Exception {lock.lock();try {// 发布新配置configService.publishConfig(nacosDataSourceProperties.getDataId(), nacosDataSourceProperties.getGroupId(),this.configEncoder.convert(value), ConfigType.JSON.getType());} finally {lock.unlock();}}@Overridepublic void close() throws Exception {}}

3、新建SentinelNacosDataSourceHandler

public class SentinelNacosDataSourceHandler implements SmartInitializingSingleton {private final SentinelProperties sentinelProperties;public SentinelNacosDataSourceHandler(SentinelProperties sentinelProperties) {this.sentinelProperties = sentinelProperties;}// 实现SmartInitializingSingleton 的接口后,当所有非懒加载的单例Bean 都初始化完成以后,Spring 的IOC 容器会调用该接口的 afterSingletonsInstantiated() 方法@Overridepublic void afterSingletonsInstantiated() {sentinelProperties.getDatasource().values().forEach(this::registryWriter);}private void registryWriter(DataSourcePropertiesConfiguration dataSourceProperties) {final NacosDataSourceProperties nacosDataSourceProperties = dataSourceProperties.getNacos();if (nacosDataSourceProperties == null) {return;}final RuleType ruleType = nacosDataSourceProperties.getRuleType();// 通过数据源配置的 ruleType 来注册数据源switch (ruleType) {case FLOW:WritableDataSource<List<FlowRule>> flowRuleWriter =new NacosWritableDataSource<>(nacosDataSourceProperties, JSON::toJSONString);WritableDataSourceRegistry.registerFlowDataSource(flowRuleWriter);break;case DEGRADE:WritableDataSource<List<DegradeRule>> degradeRuleWriter =new NacosWritableDataSource<>(nacosDataSourceProperties, JSON::toJSONString);WritableDataSourceRegistry.registerDegradeDataSource(degradeRuleWriter);break;case PARAM_FLOW:WritableDataSource<List<ParamFlowRule>> paramFlowRuleWriter =new NacosWritableDataSource<>(nacosDataSourceProperties, JSON::toJSONString);ModifyParamFlowRulesCommandHandler.setWritableDataSource(paramFlowRuleWriter);break;case SYSTEM:WritableDataSource<List<SystemRule>> systemRuleWriter =new NacosWritableDataSource<>(nacosDataSourceProperties, JSON::toJSONString);WritableDataSourceRegistry.registerSystemDataSource(systemRuleWriter);break;case AUTHORITY:WritableDataSource<List<AuthorityRule>> authRuleWriter =new NacosWritableDataSource<>(nacosDataSourceProperties, JSON::toJSONString);WritableDataSourceRegistry.registerAuthorityDataSource(authRuleWriter);break;default:break;}}
}

4、添加SentinelNacosDataSourceHandler管理

@Configuration(proxyBeanMethods = false)
@AutoConfigureAfter(SentinelAutoConfiguration.class)
public class SentinelNacosDataSourceConfiguration {@Bean@ConditionalOnMissingBeanpublic SentinelNacosDataSourceHandler sentinelNacosDataSourceHandler(SentinelProperties sentinelProperties) {return new SentinelNacosDataSourceHandler(sentinelProperties);}}

5、添加yml配置

spring:cloud:nacos:sentinel:transport:dashboard: 192.168.252.212:11111eager: trueweb-context-unify: true #是否统一web上下文,默认truedatasource:flow-manage: # 流控管理(这个名称可以自定义)nacos:namespace: sentinelgroup-id: SENTINEL_GROUPdata-id: ${spring.application.name}-flow-rulesserver-addr: ${spring.cloud.nacos.server-addr}username: ${spring.cloud.nacos.username}password: ${spring.cloud.nacos.password}data-type: jsonrule-type: flow # 指定文件配置的是那种规则degrade-manage: # 熔断管理(这个名称可以自定义)nacos:namespace: sentinelgroup-id: SENTINEL_GROUPdata-id: ${spring.application.name}-degrade-rulesserver-addr: ${spring.cloud.nacos.server-addr}username: ${spring.cloud.nacos.username}password: ${spring.cloud.nacos.password}data-type: jsonrule-type: degradehot-param-manage: # 热点参数管理(这个名称可以自定义)nacos:namespace: sentinelgroup-id: SENTINEL_GROUPdata-id: ${spring.application.name}-param-rulesserver-addr: ${spring.cloud.nacos.server-addr}username: ${spring.cloud.nacos.username}password: ${spring.cloud.nacos.password}data-type: jsonrule-type: param-flow

现在在Sentinel Dashboard 中新建规则即可自动同步到nacos中

二、sentinel-dashboard源码修改:

1、在pom.xml中把sentinel-datasource-nacos依赖的scope注释掉。

        <dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-datasource-nacos</artifactId><!--<scope>test</scope>--></dependency>
二、流控规则

1、在com.alibaba.csp.sentinel.dashboard.rule目录下创建一个nacos目录,并将test包下的 FlowRuleNacosProvider、FlowRuleNacosPublisher、NacosConfig 和 NacosConfigUtils都粘贴到nacos目录

2、新增NacosPropertiesConfiguration配置类

@Configuration
@ConfigurationProperties(prefix = "sentinel.nacos")
public class NacosPropertiesConfiguration {private String serverAddr;private String dataId;private String groupId;private String namespace;private String username;private String password;public String getServerAddr() {return serverAddr;}public void setServerAddr(String serverAddr) {this.serverAddr = serverAddr;}public String getDataId() {return dataId;}public void setDataId(String dataId) {this.dataId = dataId;}public String getGroupId() {return groupId;}public void setGroupId(String groupId) {this.groupId = groupId;}public String getNamespace() {return namespace;}public void setNamespace(String namespace) {this.namespace = namespace;}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;}
}

3、application.properties添加naocs配置

sentinel.nacos.serverAddr=******
sentinel.nacos.username=******
sentinel.nacos.password=******
sentinel.nacos.namespace=sentinel

4、修改 NacosConfig 类以支持自定义配置

//    @Bean
//    public ConfigService nacosConfigService() throws Exception {
//        return ConfigFactory.createConfigService("localhost");
//    }@Beanpublic ConfigService nacosConfigService(NacosPropertiesConfiguration nacosPropertiesConfiguration) throws Exception {Properties properties = new Properties();properties.put(PropertyKeyConst.SERVER_ADDR, nacosPropertiesConfiguration.getServerAddr());properties.put(PropertyKeyConst.NAMESPACE, nacosPropertiesConfiguration.getNamespace());properties.put(PropertyKeyConst.USERNAME, nacosPropertiesConfiguration.getUsername());properties.put(PropertyKeyConst.PASSWORD, nacosPropertiesConfiguration.getPassword());return ConfigFactory.createConfigService(properties);}

5、修改 FlowRuleNacosPublisher 确认配置文件格式为JSON

6、配置 V2 版本 Controller 调用 Nacos 提供的服务层

7、前端页面源码修改

文件路径: src/main/webapp/resources/app/scripts/controllers/identity.js
操作: 将 FlowServiceV1 改为 FlowServiceV2,将 /dashboard/flow/ 改为 /dashboard/v2/flow/。

文件路径: src/main/webapp/resources/app/scripts/directives/sidebar/sidebar.html

操作: 搜索 dashboard.flowV1 并定位到第 57 行,去掉 V1

文件路径: src/main/webapp/resources/app/views/flow_v2.html

操作: 注释掉回到单机页面的按钮。

三、熔断规则

新增DegradeRuleNacosProvider:

@Component("degradeRuleNacosProvider")
public class DegradeRuleNacosProvider implements DynamicRuleProvider<List<DegradeRuleEntity>> {@Autowiredprivate ConfigService configService;@Autowiredprivate Converter<String, List<DegradeRuleEntity>> converter;@Overridepublic List<DegradeRuleEntity> getRules(String appName) throws Exception {String rules = configService.getConfig(appName + NacosConfigUtil.DEFRADE_DATA_ID_POSTFIX,NacosConfigUtil.GROUP_ID, 3000);if (StringUtil.isEmpty(rules)) {return new ArrayList<>();}return converter.convert(rules);}
}

新增DegradeRuleNacosPublisher:

@Component("degradeRuleNacosPublisher")
public class DegradeRuleNacosPublisher implements DynamicRulePublisher<List<DegradeRuleEntity>> {@Autowiredprivate ConfigService configService;@Autowiredprivate Converter<List<DegradeRuleEntity>, String> converter;@Overridepublic void publish(String app, List<DegradeRuleEntity> rules) throws Exception {AssertUtil.notEmpty(app, "app name cannot be empty");if (rules == null) {return;}configService.publishConfig(app + NacosConfigUtil.DEFRADE_DATA_ID_POSTFIX,NacosConfigUtil.GROUP_ID, converter.convert(rules), ConfigType.JSON.getType());}
}

NacosConfigUtil类新增:

public static final String DEFRADE_DATA_ID_POSTFIX = "-degrade-rules";

修改DegradeController:

@RestController
@RequestMapping("/degrade")
public class DegradeController {private final Logger logger = LoggerFactory.getLogger(DegradeController.class);@Autowiredprivate RuleRepository<DegradeRuleEntity, Long> repository;@Autowiredprivate SentinelApiClient sentinelApiClient;@Autowiredprivate AppManagement appManagement;@Autowired@Qualifier("degradeRuleNacosProvider")private DynamicRuleProvider<List<DegradeRuleEntity>> ruleProvider;@Autowired@Qualifier("degradeRuleNacosPublisher")private DynamicRulePublisher<List<DegradeRuleEntity>> rulePublisher;@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 {//List<DegradeRuleEntity> rules = sentinelApiClient.fetchDegradeRuleOfMachine(app, ip, port);List<DegradeRuleEntity> rules = ruleProvider.getRules(app);rules = repository.saveAll(rules);return Result.ofSuccess(rules);} catch (Throwable throwable) {logger.error("queryApps error:", throwable);return Result.ofThrowable(-1, throwable);}}@PostMapping("/rule")@AuthAction(PrivilegeType.WRITE_RULE)public Result<DegradeRuleEntity> apiAddRule(@RequestBody DegradeRuleEntity entity) {Result<DegradeRuleEntity> checkResult = checkEntityInternal(entity);if (checkResult != null) {return checkResult;}Date date = new Date();entity.setGmtCreate(date);entity.setGmtModified(date);try {entity = repository.save(entity);publishRules(entity.getApp());} catch (Throwable t) {logger.error("Failed to add new degrade rule, app={}, ip={}", entity.getApp(), entity.getIp(), t);return Result.ofThrowable(-1, t);}return Result.ofSuccess(entity);}@PutMapping("/rule/{id}")@AuthAction(PrivilegeType.WRITE_RULE)public Result<DegradeRuleEntity> apiUpdateRule(@PathVariable("id") Long id,@RequestBody DegradeRuleEntity entity) {if (id == null || id <= 0) {return Result.ofFail(-1, "id can't be null or negative");}DegradeRuleEntity oldEntity = repository.findById(id);if (oldEntity == null) {return Result.ofFail(-1, "Degrade rule does not exist, id=" + id);}entity.setApp(oldEntity.getApp());entity.setIp(oldEntity.getIp());entity.setPort(oldEntity.getPort());entity.setId(oldEntity.getId());Result<DegradeRuleEntity> checkResult = checkEntityInternal(entity);if (checkResult != null) {return checkResult;}entity.setGmtCreate(oldEntity.getGmtCreate());entity.setGmtModified(new Date());try {entity = repository.save(entity);publishRules(entity.getApp());} catch (Throwable t) {logger.error("Failed to save degrade rule, id={}, rule={}", id, entity, t);return Result.ofThrowable(-1, t);}return Result.ofSuccess(entity);}@DeleteMapping("/rule/{id}")@AuthAction(PrivilegeType.DELETE_RULE)public Result<Long> delete(@PathVariable("id") Long id) {if (id == null) {return Result.ofFail(-1, "id can't be null");}DegradeRuleEntity oldEntity = repository.findById(id);if (oldEntity == null) {return Result.ofSuccess(null);}try {repository.delete(id);publishRules(oldEntity.getApp());} catch (Throwable throwable) {logger.error("Failed to delete degrade rule, id={}", id, throwable);return Result.ofThrowable(-1, throwable);}return Result.ofSuccess(id);}//    private boolean publishRules(String app, String ip, Integer port) {
//        List<DegradeRuleEntity> rules = repository.findAllByMachine(MachineInfo.of(app, ip, port));
//        return sentinelApiClient.setDegradeRuleOfMachine(app, ip, port, rules);
//    }private void publishRules(/*@NonNull*/ String app) throws Exception {List<DegradeRuleEntity> rules = repository.findAllByApp(app);rulePublisher.publish(app, rules);}private <R> Result<R> checkEntityInternal(DegradeRuleEntity entity) {if (StringUtil.isBlank(entity.getApp())) {return Result.ofFail(-1, "app can't be blank");}if (StringUtil.isBlank(entity.getIp())) {return Result.ofFail(-1, "ip can't be null or empty");}if (!appManagement.isValidMachineOfApp(entity.getApp(), entity.getIp())) {return Result.ofFail(-1, "given ip does not belong to given app");}if (entity.getPort() == null || entity.getPort() <= 0) {return Result.ofFail(-1, "invalid port: " + entity.getPort());}if (StringUtil.isBlank(entity.getLimitApp())) {return Result.ofFail(-1, "limitApp can't be null or empty");}if (StringUtil.isBlank(entity.getResource())) {return Result.ofFail(-1, "resource can't be null or empty");}Double threshold = entity.getCount();if (threshold == null || threshold < 0) {return Result.ofFail(-1, "invalid threshold: " + threshold);}Integer recoveryTimeoutSec = entity.getTimeWindow();if (recoveryTimeoutSec == null || recoveryTimeoutSec <= 0) {return Result.ofFail(-1, "recoveryTimeout should be positive");}Integer strategy = entity.getGrade();if (strategy == null) {return Result.ofFail(-1, "circuit breaker strategy cannot be null");}if (strategy < CircuitBreakerStrategy.SLOW_REQUEST_RATIO.getType()|| strategy > RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT) {return Result.ofFail(-1, "Invalid circuit breaker strategy: " + strategy);}if (entity.getMinRequestAmount() == null || entity.getMinRequestAmount() <= 0) {return Result.ofFail(-1, "Invalid minRequestAmount");}if (entity.getStatIntervalMs() == null || entity.getStatIntervalMs() <= 0) {return Result.ofFail(-1, "Invalid statInterval");}if (strategy == RuleConstant.DEGRADE_GRADE_RT) {Double slowRatio = entity.getSlowRatioThreshold();if (slowRatio == null) {return Result.ofFail(-1, "SlowRatioThreshold is required for slow request ratio strategy");} else if (slowRatio < 0 || slowRatio > 1) {return Result.ofFail(-1, "SlowRatioThreshold should be in range: [0.0, 1.0]");}} else if (strategy == RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO) {if (threshold > 1) {return Result.ofFail(-1, "Ratio threshold should be in range: [0.0, 1.0]");}}return null;}
}

NacosConfig类新增:

    @Beanpublic Converter<List<DegradeRuleEntity>, String> degradeRuleEntityEncoder() {return JSON::toJSONString;}@Beanpublic Converter<String, List<DegradeRuleEntity>> degradeRuleEntityDecoder() {return s -> JSON.parseArray(s, DegradeRuleEntity.class);}
四、热点参数

新增ParamRuleNacosProvider

@Component("paramRuleNacosProvider")
public class ParamRuleNacosProvider implements DynamicRuleProvider<List<ParamFlowRuleEntity>> {@Autowiredprivate ConfigService configService;@Autowiredprivate Converter<String, List<ParamFlowRuleEntity>> converter;@Overridepublic List<ParamFlowRuleEntity> getRules(String appName) throws Exception {String rules = configService.getConfig(appName + NacosConfigUtil.PARAM_FLOW_DATA_ID_POSTFIX,NacosConfigUtil.GROUP_ID, 3000);if (StringUtil.isEmpty(rules)) {return new ArrayList<>();}return converter.convert(rules);}
}

新增ParamRuleNacosPublisher

@Component("paramRuleNacosPublisher")
public class ParamRuleNacosPublisher implements DynamicRulePublisher<List<ParamFlowRuleEntity>> {@Autowiredprivate ConfigService configService;@Autowiredprivate Converter<List<ParamFlowRuleEntity>, String> converter;@Overridepublic void publish(String app, List<ParamFlowRuleEntity> rules) throws Exception {AssertUtil.notEmpty(app, "app name cannot be empty");if (rules == null) {return;}configService.publishConfig(app + NacosConfigUtil.PARAM_FLOW_DATA_ID_POSTFIX,NacosConfigUtil.GROUP_ID, converter.convert(rules), ConfigType.JSON.getType());}
}

NacosConfigUtil类新增:

public static final String PARAM_FLOW_DATA_ID_POSTFIX = "-param-rules";

修改ParamFlowRuleController

@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;@Autowired@Qualifier("paramRuleNacosProvider")private DynamicRuleProvider<List<ParamFlowRuleEntity>> ruleProvider;@Autowired@Qualifier("paramRuleNacosPublisher")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 {
//            return sentinelApiClient.fetchParamFlowRulesOfMachine(app, ip, port)
//                .thenApply(repository::saveAll)
//                .thenApply(Result::ofSuccess)
//                .get();List<ParamFlowRuleEntity> rules = ruleProvider.getRules(app);rules = repository.saveAll(rules);return Result.ofSuccess(rules);} 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;}@PostMapping("/rule")@AuthAction(AuthService.PrivilegeType.WRITE_RULE)public Result<ParamFlowRuleEntity> apiAddParamFlowRule(@RequestBody ParamFlowRuleEntity entity) {Result<ParamFlowRuleEntity> checkResult = checkEntityInternal(entity);if (checkResult != null) {return checkResult;}if (!checkIfSupported(entity.getApp(), entity.getIp(), entity.getPort())) {return unsupportedVersion();}entity.setId(null);entity.getRule().setResource(entity.getResource().trim());Date date = new Date();entity.setGmtCreate(date);entity.setGmtModified(date);try {entity = repository.save(entity);publishRules(entity.getApp());return Result.ofSuccess(entity);} catch (ExecutionException ex) {logger.error("Error when adding new 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 adding new parameter flow rules", throwable);return Result.ofFail(-1, throwable.getMessage());}}private <R> Result<R> checkEntityInternal(ParamFlowRuleEntity entity) {if (entity == null) {return Result.ofFail(-1, "bad rule body");}if (StringUtil.isBlank(entity.getApp())) {return Result.ofFail(-1, "app can't be null or empty");}if (StringUtil.isBlank(entity.getIp())) {return Result.ofFail(-1, "ip can't be null or empty");}if (entity.getPort() == null || entity.getPort() <= 0) {return Result.ofFail(-1, "port can't be null");}if (entity.getRule() == null) {return Result.ofFail(-1, "rule can't be null");}if (StringUtil.isBlank(entity.getResource())) {return Result.ofFail(-1, "resource name cannot be null or empty");}if (entity.getCount() < 0) {return Result.ofFail(-1, "count should be valid");}if (entity.getGrade() != RuleConstant.FLOW_GRADE_QPS) {return Result.ofFail(-1, "Unknown mode (blockGrade) for parameter flow control");}if (entity.getParamIdx() == null || entity.getParamIdx() < 0) {return Result.ofFail(-1, "paramIdx should be valid");}if (entity.getDurationInSec() <= 0) {return Result.ofFail(-1, "durationInSec should be valid");}if (entity.getControlBehavior() < 0) {return Result.ofFail(-1, "controlBehavior should be valid");}return null;}@PutMapping("/rule/{id}")@AuthAction(AuthService.PrivilegeType.WRITE_RULE)public Result<ParamFlowRuleEntity> apiUpdateParamFlowRule(@PathVariable("id") Long id,@RequestBody ParamFlowRuleEntity entity) {if (id == null || id <= 0) {return Result.ofFail(-1, "Invalid id");}ParamFlowRuleEntity oldEntity = repository.findById(id);if (oldEntity == null) {return Result.ofFail(-1, "id " + id + " does not exist");}Result<ParamFlowRuleEntity> checkResult = checkEntityInternal(entity);if (checkResult != null) {return checkResult;}if (!checkIfSupported(entity.getApp(), entity.getIp(), entity.getPort())) {return unsupportedVersion();}entity.setId(id);Date date = new Date();entity.setGmtCreate(oldEntity.getGmtCreate());entity.setGmtModified(date);try {entity = repository.save(entity);publishRules(entity.getApp());return Result.ofSuccess(entity);} catch (ExecutionException ex) {logger.error("Error when updating parameter flow rules, id=" + id, ex.getCause());if (isNotSupported(ex.getCause())) {return unsupportedVersion();} else {return Result.ofThrowable(-1, ex.getCause());}} catch (Throwable throwable) {logger.error("Error when updating parameter flow rules, id=" + id, throwable);return Result.ofFail(-1, throwable.getMessage());}}@DeleteMapping("/rule/{id}")@AuthAction(PrivilegeType.DELETE_RULE)public Result<Long> apiDeleteRule(@PathVariable("id") Long id) {if (id == null) {return Result.ofFail(-1, "id cannot be null");}ParamFlowRuleEntity oldEntity = repository.findById(id);if (oldEntity == null) {return Result.ofSuccess(null);}try {repository.delete(id);publishRules(oldEntity.getApp());return Result.ofSuccess(id);} catch (ExecutionException ex) {logger.error("Error when deleting 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 deleting parameter flow rules", throwable);return Result.ofFail(-1, throwable.getMessage());}}//    private CompletableFuture<Void> publishRules(String app, String ip, Integer port) {
//        List<ParamFlowRuleEntity> rules = repository.findAllByMachine(MachineInfo.of(app, ip, port));
//        return sentinelApiClient.setParamFlowRuleOfMachine(app, ip, port, rules);
//    }private void publishRules(/*@NonNull*/ String app) throws Exception {List<ParamFlowRuleEntity> rules = repository.findAllByApp(app);rulePublisher.publish(app, rules);}private <R> Result<R> unsupportedVersion() {return Result.ofFail(4041,"Sentinel client not supported for parameter flow control (unsupported version or dependency absent)");}private final SentinelVersion version020 = new SentinelVersion().setMinorVersion(2);
}

NacosConfig类新增:

    @Beanpublic Converter<List<ParamFlowRuleEntity>, String> paramRuleEntityEncoder() {return JSON::toJSONString;}@Beanpublic Converter<String, List<ParamFlowRuleEntity>> paramRuleEntityDecoder() {return s -> JSON.parseArray(s, ParamFlowRuleEntity.class);}
五、客户端配置

pom添加依赖

        <dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-datasource-nacos</artifactId></dependency>

yml文件添加配置

spring:cloud:sentinel:transport:dashboard: 127.0.0.1:8080eager: trueweb-context-unify: true #是否统一web上下文,默认truedatasource:flow-manage: # 流控管理(这个名称可以自定义)nacos:namespace: sentinelgroup-id: SENTINEL_GROUPdata-id: ${spring.application.name}-flow-rulesserver-addr: ${spring.cloud.nacos.server-addr}username: ${spring.cloud.nacos.username}password: ${spring.cloud.nacos.password}data-type: jsonrule-type: flow # 指定文件配置的是那种规则degrade-manage: # 熔断管理(这个名称可以自定义)nacos:namespace: sentinelgroup-id: SENTINEL_GROUPdata-id: ${spring.application.name}-degrade-rulesserver-addr: ${spring.cloud.nacos.server-addr}username: ${spring.cloud.nacos.username}password: ${spring.cloud.nacos.password}data-type: jsonrule-type: degradehot-param-manage: # 热点参数管理(这个名称可以自定义)nacos:namespace: sentinelgroup-id: SENTINEL_GROUPdata-id: ${spring.application.name}-param-rulesserver-addr: ${spring.cloud.nacos.server-addr}username: ${spring.cloud.nacos.username}password: ${spring.cloud.nacos.password}data-type: jsonrule-type: param-flow

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

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

相关文章

Kubernetes (k8s)

Kubernetes (k8s) 以下是一份 ​Kubernetes (k8s) 基础使用教程&#xff0c;涵盖从环境搭建到核心操作的完整流程&#xff0c;附详细命令和示例&#xff1a; &#x1f680; ​一、环境准备&#xff08;3种方式&#xff09;​​ ​1. 本地开发环境&#xff08;推荐&#xff09;​…

三打ANSYS HFSS

2. 激励方式&#xff08;端口&#xff09;详细对比分析在HFSS中&#xff0c;“激励方式”和“端口”这两个词经常混用&#xff0c;但严格来说&#xff0c;“端口”是实现“激励”的一种最主要的方式。端口类型工作原理适用情况优点缺点波端口 (Wave Port)默认首选。计算端口的固…

3.python——数据类型转换

python的数据类型转换分为两种&#xff1a; 隐式转换&#xff1a;自动完成 显式转换&#xff1a;用类型函数转换 隐式转换 # 自动转为浮点数 num_int 123 num_flo 1.23num_new num_int num_flo显式转换 整型 x int(1) # x 输出结果为 1 y int(2.8) # y 输出结果为 2 z …

迅为RK3568开发板OpenHarmonyv3.2-Beta4版本测试-命令终端

将串口连接到开发板的调试串口&#xff0c;进入 OpenHarmony 系统后&#xff0c;会自动进入 OpenHarmony终端&#xff0c;如下图所示&#xff1a;

【面试题】介绍一下BERT和GPT的训练方式区别?

BERT(双向编码器): 预训练任务: 掩码语言模型(MLM):随机掩盖15%的token,其中: 80%替换为[MASK] 10%替换为随机token 10%保持原样 下一句预测(NSP):判断两个句子是否连续(后续版本已移除) 训练特点: 使用双向Transformer编码器 同时利用左右上下文信息 适合理解类任…

邪修实战系列(1)

1、第一阶段邪修实战总览&#xff08;9.1-9.30&#xff09; 把第一阶段&#xff08;基础夯实期&#xff09;的学习计划拆解成极具操作性的每日行动方案。这个计划充分利用我“在职学习”的特殊优势&#xff0c;强调“用输出倒逼输入”&#xff0c;确保每一分钟的学习都直接服务…

XR数字融合工作站打造智能制造专业学习新范式

智能制造是工业4.0的核心发展方向&#xff0c;涵盖数字化设计、智能生产、工业机器人、数字孪生、物联网等关键技术。然而&#xff0c;传统教学模式在设备成本高、实训风险大、抽象概念难理解等方面存在诸多挑战。XR数字融合工作站,利用VR/AR/MR等技术&#xff0c;通过虚拟仿真…

基于FPGA实现数字QAM调制系统

基于FPGA实现数字QAM调制系统题目要求一、代码设计1.顶层2.分频3.m序列4.串转并5.映射6.正弦波余弦波生成ROM和7.ask二、仿真波形总结题目要求 FPGA实现数字QAM调制系统要求根据正交振幅调制原理&#xff0c;利用正弦载波信号发生器&#xff0c;实现调制信号。调制原理会利用到…

DAY 22 复习日

浙大疏锦行复习日 仔细回顾一下之前21天的内容&#xff0c;没跟上进度的同学补一下进度。 作业&#xff1a; 自行学习参考如何使用kaggle平台&#xff0c;写下使用注意点&#xff0c;并对下述比赛提交代码 导入需要的库 import pandas as pd # 用于数据处理和分析&#xff0c;…

biocmanager安装 库 老是提示网络连接错误 才尝试各种办法

您好&#xff0c;遇到 BioManager &#xff08;通常是 BiocManager&#xff09;安装R包时提示网络连接错误确实非常令人头疼。这通常与R/RStudio的配置、网络环境&#xff08;尤其是国内用户&#xff09;或SSL证书问题有关。 请不要着急&#xff0c;我们可以按照从易到难的顺序…

【开题答辩全过程】以 智能商品数据分析系统为例,包含答辩的问题和答案

个人简介一名14年经验的资深毕设内行人&#xff0c;语言擅长Java、php、微信小程序、Python、Golang、安卓Android等开发项目包括大数据、深度学习、网站、小程序、安卓、算法。平常会做一些项目定制化开发、代码讲解、答辩教学、文档编写、也懂一些降重方面的技巧。感谢大家的…

解构复杂财务逆向业务:如何优雅地生成与管理负数单?

文章目录一 核心复杂性二 关键设计模式&#xff1a;三 棘手场景与解决方案&#xff1a;1.分批合并处理&#xff1a;负数单需能智能拆分&#xff0c;精准冲销多批次的正向单据。2.优先级问题&#xff1a;3.超额处理&#xff1a;系统应坚决拦截而非处理&#xff0c;防止资金损失和…

Android集成OpenCV4实例

Android集成OpenCV4分以下几步骤&#xff1a; 使用Android Studio Giraffe | 2022.3.1创建一个Empty Views Activity空项目&#xff0c;包名为&#xff1a;com.example.andopencvdemo00 &#xff0c; 创建成功后&#xff0c;进行以下相关设置&#xff1a; 第一步&#xff1a;在…

npy可视化方法

npviewer 是一个应用程序&#xff0c;它允许您以热图的形式可视化 numpy 的 npy 文件中的数据。该应用程序根据不同的模式自动选择适当的维度进行显示。 根据不同的模式自动选择适当的维度进行显示支持不同格式的 numpy 数据的可视化&#xff0c;如 RGB 和灰度用户友好的界面使…

【Cesium】介绍及基础使用

文章目录一、Cesium 介绍二、 使用1、引入 cesium2、Viewer 配置选项1. 基础控件配置2. 场景与渲染配置3. 地形配置4. 天空与大气效果3、坐标系系统3.1 地理坐标系3.2 笛卡尔空间直角坐标系3.3 屏幕坐标系4、Entity 实体4.1 简介4.2 Entity 常见图形类型Point 点Polyline 线Pol…

基于SpringBoot的运动服装销售系统【2026最新】

作者&#xff1a;计算机学姐 开发技术&#xff1a;SpringBoot、SSM、Vue、MySQL、JSP、ElementUI、Python、小程序等&#xff0c;“文末源码”。 专栏推荐&#xff1a;前后端分离项目源码、SpringBoot项目源码、Vue项目源码、SSM项目源码、微信小程序源码 精品专栏&#xff1a;…

【嵌入式DIY实例-ESP32篇】-倾斜弹跳球游戏

倾斜弹跳球游戏 文章目录 倾斜弹跳球游戏 1、MPU6050介绍 2、硬件准备与接线 3、代码实现 在这个交互式 ESP32 Arduino 项目中,我们模拟了一个绿色球体在全彩 ST7789 170320 LCD 屏幕上弹跳,完全由 MPU6050 陀螺仪的运动控制。当你倾斜传感器时,球体会呈现出逼真的物理运动,…

从spring MVC角度理解HTTP协议及Request-Response模式

什么是HTTP协议&#xff1f;HTTP协议&#xff08;HyperText Transfer Protocol&#xff0c;超文本传输协议&#xff09;是一种通信规则&#xff0c;它定义了客户端&#xff08;如浏览器、手机APP&#xff09; 和服务器 之间如何交换信息&#xff0c;是用于在万维网&#xff08;…

江协科技STM32学习笔记补充之003 :STM32复位电路的详细分析

电路作用与每个器件R1&#xff08;10 kΩ&#xff0c;上拉到 3V3&#xff09;让 NRST 在无外力时保持高电平&#xff1d;不复位&#xff1b;同时与电容形成 RC&#xff0c;决定上电复位延时。阻值不能太小&#xff08;否则调试器或芯片复位驱动下拉电流太大&#xff09;&#x…

Spring Boot HTTP状态码详解

Spring Boot HTTP状态码完全指南&#xff1a;从入门到精通 前言 在RESTful API开发中&#xff0c;HTTP状态码是与客户端通信的重要桥梁。Spring Boot通过HttpStatus枚举提供了完整的HTTP状态码支持。本文将深入解析这些状态码的含义、使用场景以及在Spring Boot中的最佳实践。 …