sentinel持久化配置至nacos

持久化至nacos需改造sentinel控制台

sentinel版本1.8.3

1、修改pom文件,去除sentinel 连接nacos jar包限制

<!-- for Nacos rule publisher sample -->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-nacos</artifactId>
            <!--<scope>test</scope>-->
        </dependency>

2、application.properties 文件新增配置(也在NacosConfig.nacosConfigService()中配置)


nacos.address=localhost:8848
nacos.namespace=

3、复制test中的模板

网关流控需要新建

GatewayFlowRuleNacosProvider
package com.alibaba.csp.sentinel.dashboard.rule.nacos;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayFlowRuleEntity;
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.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component("gatewayFlowRuleNacosProvider")
public class GatewayFlowRuleNacosProvider implements DynamicRuleProvider<List<GatewayFlowRuleEntity>> {

    @Autowired
    private ConfigService configService;
    @Autowired
    private Converter<String, List<GatewayFlowRuleEntity>> converter;

    @Override
    public List<GatewayFlowRuleEntity> getRules(String appName) throws Exception {
        String rules = configService.getConfig(appName + NacosConfigUtil.GATEWAY_FLOW_DATA_ID_POSTFIX,
            NacosConfigUtil.GROUP_ID, 3000);
        if (StringUtil.isEmpty(rules)) {
            return new ArrayList<>();
        }
        return converter.convert(rules);
    }
}
GatewayFlowRuleNacosPublisher
package com.alibaba.csp.sentinel.dashboard.rule.nacos;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayFlowRuleEntity;
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.stereotype.Component;

import java.util.List;

@Component("gatewayFlowRuleNacosPublisher")
public class GatewayFlowRuleNacosPublisher implements DynamicRulePublisher<List<GatewayFlowRuleEntity>> {

    @Autowired
    private ConfigService configService;
    @Autowired
    private Converter<List<GatewayFlowRuleEntity>, String> converter;

    @Override
    public 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.GATEWAY_FLOW_DATA_ID_POSTFIX,
            NacosConfigUtil.GROUP_ID, converter.convert(rules));
    }
}

NacosConfig
package com.alibaba.csp.sentinel.dashboard.rule.nacos;

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;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Configuration
public class NacosConfig {

    @Bean
    public Converter<List<FlowRuleEntity>, String> flowRuleEntityEncoder() {
        return JSON::toJSONString;
    }

    @Bean
    public Converter<String, List<FlowRuleEntity>> flowRuleEntityDecoder() {
        return s -> JSON.parseArray(s, FlowRuleEntity.class);
    }

    @Bean
    public Converter<List<GatewayFlowRuleEntity>, String> gatewayFlowRuleEntityEncoder() {
        return JSON::toJSONString;
    }

    @Bean
    public Converter<String, List<GatewayFlowRuleEntity>> gatewayFlowRuleEntityDecoder() {
        return s -> JSON.parseArray(s, GatewayFlowRuleEntity.class);
    }

    @Bean
    public ConfigService nacosConfigService() throws Exception {
        return ConfigFactory.createConfigService("localhost");
    }
}

NacosConfigUtil

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 GATEWAY_FLOW_DATA_ID_POSTFIX = "-gateway-flow-rules";
    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() {}
}

 修改GatewayFlowRuleController

使用gatewayFlowRuleNacosProvider和gatewayFlowRuleNacosPublisher替换 sentinelApiClient

/*    @Autowired
    private SentinelApiClient sentinelApiClient;*/

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

### 配置 Sentinel 将流量控制和熔断规则持久化保存至 Nacos 为了使 Sentinel 的流量控制和熔断规则能够持久化存储到 Nacos 中,需完成一系列配置工作。这不仅涉及到了解如何调整应用本身的属性文件来连接 NacosSentinel 控制台,还涉及到理解不同类型的熔断策略以及它们的工作机制。 #### 应用程序配置 在项目的 `application.properties` 文件中加入必要的配置项以便与 NacosSentinel 进行交互: ```properties server.port=9100 csp.sentinel.dashboard.server=localhost:8080 project.name=sentinel-dashboard sentinel.nacos.serverAddr=127.0.0.1:8848 sentinel.nacos.username=nacos sentinel.nacos.password=nacos sentinel.nacos.namespace= ``` 上述配置指定了服务监听端口、Sentinel 控制台地址和服务名,并设置了访问 Nacos 所需的信息[^3]。 #### 数据源整合 为了让 Sentinel 能够读取来自 Nacos配置并将其应用于应用程序中的限流或熔断逻辑,需要通过编程方式注册一个 Nacos 数据源给 Sentinel。此过程通常是在 Spring Boot 或其他框架启动期间执行的一次性操作,在代码层面实现数据源的绑定。 对于 Java 开发者来说,可以通过如下所示的方式创建自定义类来进行初始化设置: ```java import com.alibaba.csp.sentinel.datasource.ReadableDataSource; import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; // ... 导入其他必要包 ... @Configuration public class SentinelConfig { @Value("${spring.application.name}") private String applicationName; @Bean public void initFlowRules() { ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new NacosDataSource.Builder() .dataId(applicationName + "-flow-rules") .group("DEFAULT_GROUP") .sourceHandler(source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {})) .build(); FlowRuleManager.register2Property(flowRuleDataSource.getProperty()); } } ``` 这段代码展示了如何利用 Nacos SDK 创建一个可读的数据源实例 (`ReadableDataSource`) 并关联到特定的应用名称下对应的流控规则集合上;之后再把这个数据源注册进 Sentinel 流量控制器管理器(`FlowRuleManager`)里去[^1]。 #### 熔断策略说明 除了简单的流量控制外,Sentinel 支持多种复杂的熔断降级策略,比如基于慢调用比例(SLOW_REQUEST_RATIO)触发熔断保护。在这种情况下,开发者可以指定最大响应时间和最小请求数目作为判断条件之一。一旦满足这些条件,系统将在一段时间内拒绝新的请求直到恢复正常状态[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值