Nacos除了服务注册中心,还集成了配置中心。本篇就从Nacos的配置中心的客户端源码入手。分析Nacos客户端是如何获取到Nacos服务的配置文件的。
分析源码的第一步是找到入口,官方再次给了我们一个注册中心的样例代码,在源码的nacos-example工程中。先看下这部分的代码。
publicstaticvoidmain(String[] args)throws NacosException, InterruptedException {
StringserverAddr="localhost";
StringdataId="test";
Stringgroup="DEFAULT_GROUP";
Propertiesproperties=newProperties();
properties.put("serverAddr", serverAddr);
// 通过工厂模式创建了一个ConfigService服务
ConfigServiceconfigService= NacosFactory.createConfigService(properties);
// 获取配置信息
Stringcontent= configService.getConfig(dataId, group, 5000);
System.out.println(content);
// 添加监听器,监听对应dataId,group的配置信息
configService.addListener(dataId, group, newListener() {
@Override
publicvoidreceiveConfigInfo(String configInfo) {
System.out.println("receive:" + configInfo);
}
@Override
public Executor getExecutor() {
returnnull;
}
});
// 发布配置信息
booleanisPublishOk= configService.publishConfig(dataId, group, "content");
System.out.println(isPublishOk);
Thread.sleep(3000);
// 获取配置
content = configService.getConfig(dataId, group, 5000);
System.out.println(content);
// 移除配置
booleanisRemoveOk= configService.removeConfig(dataId, group);
System.out.println(isRemoveOk);
Thread.sleep(3000);
// 获取配置
content = configService.getConfig(dataId, group, 5000);
System.out.println(content);
Thread.sleep(300000);
}
复制代码
NacosConfigService创建
创建ConfigService实现比较简单,就是通过反射创建了NacosConfigService。只是要注意下创建NacosConfigService时会调用它的构造方法,做一些初始化的操作。
publicNacosConfigService(Properties properties)throws NacosException {
finalNacosClientPropertiesclientProperties= NacosClientProperties.PROTOTYPE.derive(properties);
ValidatorUtils.checkInitParam(clientProperties);
// 初始化Namespace
initNamespace(clientProperties);
// 创建了一个配置过滤器链,可以采用SPI扩展机制加载对应的过滤器实现类
this.configFilterChainManager = newConfigFilterChainManager(clientProperties.asProperties());
ServerListManagerserverListManager=newServerListManager(clientProperties);
// 创建了一个服务管理器,内含一个定时轮询线程池,每隔30s拉取一次服务
serverListManager.start();
// 创建了一个客户端工作者,包含了一个代理对象
this.worker = newClientWorker(this.configFilterChainManager, serverListManager, clientProperties);
// will be deleted in 2.0 later versions
agent = newServerHttpAgent(serverListManager);
}
复制代码
在下一个篇章将重点介绍一下ClientWorker,这个是个核心,所有和服务端的交互都通过它。因为本篇主要讲解客户端注册的流程框架,先不深入细节。这里只需要知道这里进行了创建。
获取配置信息
创建ConfigService后就可以通过接口获取配置信息了。