在之前的兩篇教程中我們分別介紹了如何將Sentinel的限流規(guī)則存儲(chǔ)到Nacos和Apollo中。同時(shí),在文末的思考中,我都指出了這兩套整合方案都存在一個(gè)不足之處:不論采用什么配置中心,限流規(guī)則都只能通過Nacos界面或Apollo界面來完成修改才能得到持久化存儲(chǔ),而在Sentinel Dashboard中修改限流規(guī)則雖然可以生效,但是不會(huì)被持久化到配置中心。而在這兩個(gè)配置中心里存儲(chǔ)的數(shù)據(jù)是一個(gè)Json格式,當(dāng)存儲(chǔ)的規(guī)則越來越多,對(duì)該Json配置的可讀性與可維護(hù)性會(huì)變的越來越差。所以,下面我們就來繼續(xù)探討這個(gè)不足之處,并給出相應(yīng)的解決方案。本文以Apollo存儲(chǔ)為例,下一篇介紹Nacos的改在示例。
問題分析
在實(shí)際操作之前,我們先通過下圖了解一下之前我們所實(shí)現(xiàn)的限流規(guī)則持久化方案的配置數(shù)據(jù)流向圖:

-
藍(lán)色箭頭代表了限流規(guī)則由配置中心發(fā)起修改的更新路徑 -
橙色箭頭代表了限流規(guī)則由Sentinel Dashboard發(fā)起修改的更新路徑
從圖中可以很明顯的看到,Sentinel Dashboard與業(yè)務(wù)服務(wù)之間本身是可以互通獲取最新限流規(guī)則的,這在沒有整合配置中心來存儲(chǔ)限流規(guī)則的時(shí)候就已經(jīng)存在這樣的機(jī)制。最主要的區(qū)別是:配置中心的修改都可以實(shí)時(shí)的刷新到業(yè)務(wù)服務(wù),從而被Sentinel Dashboard讀取到,但是對(duì)于這些規(guī)則的更新到達(dá)各個(gè)業(yè)務(wù)服務(wù)之后,并沒有一個(gè)機(jī)制去同步到配置中心,作為配置中心的客戶端也不會(huì)提供這樣的逆向更新方法。
改造方案
關(guān)于如何改造,現(xiàn)來解讀一下官方文檔中關(guān)于這部分的說明:
要通過 Sentinel 控制臺(tái)配置集群流控規(guī)則,需要對(duì)控制臺(tái)進(jìn)行改造。我們提供了相應(yīng)的接口進(jìn)行適配。
從 Sentinel 1.4.0 開始,我們抽取出了接口用于向遠(yuǎn)程配置中心推送規(guī)則以及拉取規(guī)則:
- DynamicRuleProvider<T>: 拉取規(guī)則
- DynamicRulePublisher<T>: 推送規(guī)則
對(duì)于集群限流的場(chǎng)景,由于每個(gè)集群限流規(guī)則都需要唯一的 flowId,因此我們建議所有的規(guī)則配置都通過動(dòng)態(tài)規(guī)則源進(jìn)行管理,并在統(tǒng)一的地方生成集群限流規(guī)則。
我們提供了新版的流控規(guī)則頁面,可以針對(duì)應(yīng)用維度推送規(guī)則,對(duì)于集群限流規(guī)則可以自動(dòng)生成 flowId。用戶只需實(shí)現(xiàn) DynamicRuleProvider 和 DynamicRulePublisher 接口,即可實(shí)現(xiàn)應(yīng)用維度推送(URL: /v2/flow)。
這段內(nèi)容什么意思呢?簡(jiǎn)單的說就是Sentinel Dashboard通過DynamicRuleProvider和DynamicRulePublisher兩個(gè)接口來獲取和更新應(yīng)用的動(dòng)態(tài)規(guī)則。默認(rèn)情況下,就如上一節(jié)中Sentinel Dashboard與各業(yè)務(wù)服務(wù)之間的兩個(gè)箭頭,一個(gè)接口負(fù)責(zé)獲取規(guī)則,一個(gè)接口負(fù)責(zé)更新規(guī)則。
所以,只需要通過這兩個(gè)接口,實(shí)現(xiàn)對(duì)配置中心中存儲(chǔ)規(guī)則的讀寫,就能實(shí)現(xiàn)Sentinel Dashboard中修改規(guī)則與配置中心存儲(chǔ)同步的效果。
具體的配置數(shù)據(jù)流向圖如下:

其中,綠色箭頭為公共公共部分,即:不論從培中心修改,還是從Sentinel Dashboard修改都會(huì)觸發(fā)的操作。這樣的話,從上圖的兩處修改起點(diǎn)看,所有涉及的部分都能獲取到一致的限流規(guī)則了。
代碼實(shí)現(xiàn)
下面繼續(xù)說說具體的代碼實(shí)現(xiàn),這里參考了Sentinel Dashboard源碼中關(guān)于Apollo實(shí)現(xiàn)的測(cè)試用例。但是由于考慮到與Spring Cloud Alibaba的結(jié)合使用,略作修改。
第一步:修改pom.xml中的Apollo OpenAPi的依賴,將<scope>test</scope>注釋掉,這樣才能在主程序中使用。
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-openapi</artifactId>
<version>1.2.0</version>
<!--<scope>test</scope>-->
</dependency>
第二步:找到resources/app/scripts/directives/sidebar/sidebar.html中的這段代碼:
<li ui-sref-active="active">
<a ui-sref="dashboard.flowV1({app: entry.app})">
<i class="glyphicon glyphicon-filter"></i> 流控規(guī)則
</a>
</li>
修改為:
<li ui-sref-active="active">
<a ui-sref="dashboard.flow({app: entry.app})">
<i class="glyphicon glyphicon-filter"></i> 流控規(guī)則
</a>
</li>
第三步:在com.alibaba.csp.sentinel.dashboard.rule包下新建一個(gè)apollo包,用來編寫針對(duì)Apollo的擴(kuò)展實(shí)現(xiàn)。
第四步:創(chuàng)建Apollo的配置類,定義Apollo的portal訪問地址以及第三方應(yīng)用訪問的授權(quán)Token(通過Apollo管理員賬戶登錄,在“開放平臺(tái)授權(quán)管理”功能中創(chuàng)建),具體代碼如下:
@Configuration
public class ApolloConfig {
@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 ApolloOpenApiClient apolloOpenApiClient() {
ApolloOpenApiClient client = ApolloOpenApiClient.newBuilder()
.withPortalUrl("https://apollo.xxx.com") // TODO 根據(jù)實(shí)際情況修改
.withToken("open api token") // TODO 根據(jù)實(shí)際情況修改
.build();
return client;
}
}
第五步:實(shí)現(xiàn)Apollo的配置拉取實(shí)現(xiàn)。
@Component("flowRuleApolloProvider")
public class FlowRuleApolloProvider implements DynamicRuleProvider<List<FlowRuleEntity>> {
@Autowired
private ApolloOpenApiClient apolloOpenApiClient;
@Autowired
private Converter<String, List<FlowRuleEntity>> converter;
@Value("${env:DEV}")
private String env;
@Override
public List<FlowRuleEntity> getRules(String appName) throws Exception {
// flowDataId對(duì)應(yīng)
String flowDataId = "sentinel.flowRules";
OpenNamespaceDTO openNamespaceDTO = apolloOpenApiClient.getNamespace(appName, env, "default", "application");
String rules = openNamespaceDTO
.getItems()
.stream()
.filter(p -> p.getKey().equals(flowDataId))
.map(OpenItemDTO::getValue)
.findFirst()
.orElse("");
if (StringUtil.isEmpty(rules)) {
return new ArrayList<>();
}
return converter.convert(rules);
}
}
-
getRules方法中的appName參數(shù)是Sentinel中的服務(wù)名稱,這里直接通過這個(gè)名字獲取Apollo配置是由于Apollo中的項(xiàng)目AppId與之一致,如果存在不一致的情況,則需要自己做轉(zhuǎn)換。 - 這里注入了一個(gè)
env屬性,主要由于我們?cè)谑褂肁pollo的時(shí)候,通過啟動(dòng)參數(shù)來控制不同環(huán)境。所以這樣就能在不同環(huán)境區(qū)分不同的限流配置了。 - 這里的
flowDataId對(duì)應(yīng)各個(gè)微服務(wù)應(yīng)用中定義的spring.cloud.sentinel.datasource.ds.apollo.flowRulesKey配置,即:Apollo中使用了什么key來存儲(chǔ)限流配置。 - 其他如Cluster、Namepsace都采用了默認(rèn)值:default和application,這個(gè)讀者有特殊需求可以做對(duì)應(yīng)的修改。
第六步:實(shí)現(xiàn)Apollo的配置推送實(shí)現(xiàn)。
@Component("flowRuleApolloPublisher")
public class FlowRuleApolloPublisher implements DynamicRulePublisher<List<FlowRuleEntity>> {
@Autowired
private ApolloOpenApiClient apolloOpenApiClient;
@Autowired
private Converter<List<FlowRuleEntity>, String> converter;
@Value("${env:DEV}")
private String env;
@Override
public void publish(String app, List<FlowRuleEntity> rules) throws Exception {
String flowDataId = "sentinel.flowRules";
AssertUtil.notEmpty(app, "app name cannot be empty");
if (rules == null) {
return;
}
OpenItemDTO openItemDTO = new OpenItemDTO();
openItemDTO.setKey(flowDataId);
openItemDTO.setValue(converter.convert(rules));
openItemDTO.setComment("modify by sentinel-dashboard");
openItemDTO.setDataChangeCreatedBy("apollo");
apolloOpenApiClient.createOrUpdateItem(app, env, "default", "application", openItemDTO);
// Release configuration
NamespaceReleaseDTO namespaceReleaseDTO = new NamespaceReleaseDTO();
namespaceReleaseDTO.setEmergencyPublish(true);
namespaceReleaseDTO.setReleaseComment("release by sentinel-dashboard");
namespaceReleaseDTO.setReleasedBy("apollo");
namespaceReleaseDTO.setReleaseTitle("release by sentinel-dashboard");
apolloOpenApiClient.publishNamespace(app, env, "default", "application", namespaceReleaseDTO);
}
}
- 這里的大部分內(nèi)容,如:env、flowDataId、app說明與上一步中的實(shí)現(xiàn)一致
-
openItemDTO.setDataChangeCreatedBy("apollo");和namespaceReleaseDTO.setReleasedBy("apollo");這兩句需要注意一下,必須設(shè)置存在并且有權(quán)限的用戶,不然會(huì)更新失敗。
第七步:修改com.alibaba.csp.sentinel.dashboard.controller.v2.FlowControllerV2中DynamicRuleProvider和DynamicRulePublisher注入的Bean,改為上面我們編寫的針對(duì)Apollo的實(shí)現(xiàn):
@Autowired
@Qualifier("flowRuleApolloProvider")
private DynamicRuleProvider<List<FlowRuleEntity>> ruleProvider;
@Autowired
@Qualifier("flowRuleApolloPublisher")
private DynamicRulePublisher<List<FlowRuleEntity>> rulePublisher;
代碼示例
本文介紹內(nèi)容的客戶端代碼,示例讀者可以通過查看下面?zhèn)}庫中的alibaba-sentinel-dashboard-apollo項(xiàng)目:
- Github:https://github.com/dyc87112/SpringCloud-Learning/
- Gitee:https://gitee.com/didispace/SpringCloud-Learning/
如果您對(duì)這些感興趣,歡迎star、follow、收藏、轉(zhuǎn)發(fā)給予支持!
系列回顧
- 《Spring Cloud Alibaba基礎(chǔ)教程:使用Nacos實(shí)現(xiàn)服務(wù)注冊(cè)與發(fā)現(xiàn)》
- 《Spring Cloud Alibaba基礎(chǔ)教程:支持的幾種服務(wù)消費(fèi)方式》
- 《Spring Cloud Alibaba基礎(chǔ)教程:使用Nacos作為配置中心》
- 《Spring Cloud Alibaba基礎(chǔ)教程:Nacos配置的加載規(guī)則詳解》
- 《Spring Cloud Alibaba基礎(chǔ)教程:Nacos配置的多環(huán)境管理》
- 《Spring Cloud Alibaba基礎(chǔ)教程:Nacos配置的多文件加載與共享配置》
- 《Spring Cloud Alibaba基礎(chǔ)教程:Nacos的數(shù)據(jù)持久化》
- 《Spring Cloud Alibaba基礎(chǔ)教程:Nacos的集群部署》
- 《Spring Cloud Alibaba基礎(chǔ)教程:使用Sentinel實(shí)現(xiàn)接口限流》
- 《Spring Cloud Alibaba基礎(chǔ)教程:Sentinel使用Nacos存儲(chǔ)規(guī)則》
- 《Spring Cloud Alibaba基礎(chǔ)教程:Sentinel使用Apollo存儲(chǔ)規(guī)則》