上一篇文章应该可以通过main方法,获得存在diamond里的值了。
那么从现在开始讲解一下diamond-client的源码。
1.DefaultDiamondManager
com.taobao.diamond.manager.impl.DefaultDiamondManager
public DefaultDiamondManager(String group, String dataId, ManagerListener managerListener) {
this.dataId = dataId;
this.group = group;
diamondSubscriber = DiamondClientFactory.getSingletonDiamondSubscriber();
this.managerListeners.add(managerListener);
((DefaultSubscriberListener) diamondSubscriber.getSubscriberListener()).addManagerListeners(this.dataId,
this.group, this.managerListeners);
diamondSubscriber.addDataId(this.dataId, this.group);
diamondSubscriber.start();
}
2.开始初始化的工作
com.taobao.diamond.client.impl.DefaultDiamondSubscriber
/**
* 启动DiamondSubscriber:<br>
* 1.阻塞主动获取所有的DataId配置信息<br>
* 2.启动定时线程定时获取所有的DataId配置信息<br>
*/
public synchronized void start() {
if (isRun) {
return;
}
if (null == scheduledExecutor || scheduledExecutor.isTerminated()) {
scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
}
localConfigInfoProcessor.start(this.diamondConfigure.getFilePath() + "/" + DATA_DIR);
serverAddressProcessor = new ServerAddressProcessor(this.diamondConfigure, this.scheduledExecutor);
serverAddressProcessor.start();
this.snapshotConfigInfoProcessor =
new SnapshotConfigInfoProcessor(this.diamondConfigure.getFilePath() + "/" + SNAPSHOT_DIR);
// 设置domainNamePos值
randomDomainNamePos();
initHttpClient();
// 初始化完毕
isRun = true;
if (log.isInfoEnabled()) {
log.info("当前使用的域名有:" + this.diamondConfigure.getDomainNameList());
}
if (MockServer.isTestMode()) {
bFirstCheck = false;
}
else {
// 设置轮询间隔时间
this.diamondConfigure.setPollingIntervalTime(Constants.POLLING_INTERVAL_TIME);
}
// 轮询
rotateCheckConfigInfo();
addShutdownHook();
}
这个方法里主要做了2件事情
2.1.获取服务器列表
public synchronized void start() {
if (isRun) {
return;
}
isRun = true;
initHttpClient();
if (this.diamondConfigure.isLocalFirst()) {
acquireServerAddressFromLocal();
}
else {
synAcquireServerAddress();
asynAcquireServerAddress();
}
}
2.2.监测dataId是否变化
/**
* 循环探测配置信息是否变化,如果变化,则再次向DiamondServer请求获取对应的配置信息
*/
private void rotateCheckConfigInfo() {
scheduledExecutor.schedule(new Runnable() {
public void run() {
if (!isRun) {
log.warn("DiamondSubscriber不在运行状态中,退出查询循环");
return;
}
try {
checkLocalConfigInfo();
checkDiamondServerConfigInfo();
checkSnapshot();
}
catch (Exception e) {
e.printStackTrace();
log.error("循环探测发生异常", e);
}
finally {
rotateCheckConfigInfo();
}
}
}, bFirstCheck ? 60 : diamondConfigure.getPollingIntervalTime(), TimeUnit.SECONDS);
bFirstCheck = false;
}
3.获取diamond存储的值
public String getAvailableConfigureInfomation(String dataId, String group, long timeout) {
// 尝试先从本地和网络获取配置信息
try {
String result = getConfigureInfomation(dataId, group, timeout);
if (result != null && result.length() > 0) {
return result;
}
}
catch (Throwable t) {
log.error(t.getMessage(), t);
}
// 测试模式不使用本地dump
if (MockServer.isTestMode()) {
return null;
}
return getSnapshotConfiginfomation(dataId, group);
}
到此,就可以取出你想要的数据了。