Spring Cloud Sentinel整合Nacos实现配置持久化
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import java.util.List;
import java.util.Properties;
public class SentinelNacosConfig {
private static final String GROUP_ID = "DEFAULT_GROUP";
private static final String FLOW_DATA_ID = "sentinel-flow-rules";
private static final String NACOS_SERVER_ADDR = "127.0.0.1:8848";
public static void main(String[] args) throws NacosException {
// 初始化配置服务
initConfigService(NACOS_SERVER_ADDR);
// 加载流控规则
loadFlowRules();
}
private static void initConfigService(String nacosServerAddr) throws NacosException {
Properties properties = new Properties();
properties.put("serverAddr", nacosServerAddr);
ConfigService configService = NacosFactory.createConfigService(properties);
// 订阅配置,并且对获取到的配置进行处理
configService.addListener(FLOW_DATA_ID, GROUP_ID, (configInfo, e) -> {
if (e == null) {
// 处理配置变化,更新规则
String content = configInfo.getContent();
updateRules(content);
}
});
}
private static void loadFlowRules() {
// 从Nacos读取流控规则配置
ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new NacosDataSource<>(FLOW_DATA_ID, GROUP_ID, content -> JSON.parseArray(content, FlowRule.class));
// 加载流控规则
FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
}
private static void updateRules(String content) {
List<FlowRule> rules = JSON.parseArray(content, FlowRule.class);
FlowRuleManager.loadRules(rules);
}
}
这段代码展示了如何使用Sentinel和Nacos进行规则配置的持久化。首先,它通过NacosFactory创建了一个ConfigService实例,用于从Nacos配置中心订阅和获取配置信息。当配置信息变更时,它会调用updateRules方法来更新本地的流控规则。这个例子简洁地展示了如何将Sentinel与Nacos整合,并实现动态规则配置。
评论已关闭