配置监听,是要重点分析,代码稍微复杂一些。
/**
* Add a listener to the configuration, after the server modified the configuration, the client will use the
* incoming listener callback. Recommended asynchronous processing, the application can implement the getExecutor
* method in the ManagerListener, provide a thread pool of execution. If provided, use the main thread callback, May
* block other configurations or be blocked by other configurations.
*
* @param dataId dataId
* @param group group
* @param listener listener
* @throws NacosException NacosException
*/
void addListener(String dataId, String group, Listener listener) throws NacosException;
1.添加监听器到CacheData
/**
* Add listeners for tenant.
*
* @param dataId dataId of data
* @param group group of data
* @param listeners listeners
* @throws NacosException nacos exception
*/
public void addTenantListeners(String dataId, String group, List<? extends Listener> listeners)
throws NacosException {
group = null2defaultGroup(group);
String tenant = agent.getTenant();
CacheData cache = addCacheDataIfAbsent(dataId, group, tenant);
for (Listener listener : listeners) {
cache.addListener(listener);
}
}
监听的配置组装,putifAbsent,cacheData不存在的话,才添加
/**
* Add cache data if absent.
*
* @param dataId data id if data
* @param group group of data
* @param tenant tenant of data
* @return cache data
*/
public CacheData addCacheDataIfAbsent(String dataId, String group, String tenant) throws NacosException {
String key = GroupKey.getKeyTenant(dataId, group, tenant);
CacheData cacheData = cacheMap.get(key);
//查看是否有缓存,有的话返回;没有的话,去服务端查找
if (cacheData != null) {
return cacheData;
}
cacheData = new CacheData(configFilterChainManager, agent.getName(), dataId, group, tenant);
// multiple listeners on the same dataid+group and race condition
CacheData lastCacheData = cacheMap.putIfAbsent(key, cacheData);
//以前没有监听的情况下,去服务