带着问题去读源码:
问题1:springboot跟nacos-config是怎么整合的(主要关心:是用到了spring中的哪些扩展点)
问题2:nacos-config是如何从服务器拉取配置的(怎么生成dataId,为何在application.yml中配置nacos.config的配置却无法生效)
问题3:使用@RefreshScope注解以后,为什么会实时的拉取数据。
springboot跟nacos-config的整合:
整体大概思路:
a:引入spring-cloud-starter-alibaba-nacos-config包
b:springboot会自动扫描该包下的META-INF下的spring.factories文件,生成BeanDefinetion。
c:这里主要看NacosConfigBootstrapConfiguration这个自动装配类(至于为什么,看类名,抓主要流程)
d:这个类中有三个Bean(NacosConfigProperties,NacosConfigManager,NacosPropertySourceLocator)
d.1:NacosConfigProperties:类上有@ConfigurationProperties(NacosConfigProperties.PREFIX),所以是存放配置的bean.
d.2:NacosConfigManager: 这里有一个无参的构造函数,Bean生成过程应该是会调用的。
public NacosConfigManager(NacosConfigProperties nacosConfigProperties) {
this.nacosConfigProperties = nacosConfigProperties;
// Compatible with older code in NacosConfigProperties,It will be deleted in the
// future. 创建ConfigService
createConfigService(nacosConfigProperties);
}
这里是通过反射获取NacosConfigService,获取带参的构造方法,在实例化。
public static ConfigService createConfigService(Properties properties) throws NacosException {
try {
Class<?> driverImplClass = Class.forName("com.alibaba.nacos.client.config.NacosConfigService");
Constructor constructor = driverImplClass.getConstructor(Properties.class);
ConfigService vendorImpl = (ConfigService) constructor.newInstance(properties);
return vendorImpl;
} catch (Throwable e) {
throw new NacosException(NacosException.CLIENT_INVALID_PARAM, e);
}
}
这里会创建两个类:MetricsHttpAgent,ClientWorker
public NacosConfigService(Properties properties) throws NacosException {
String encodeTmp = properties.getProperty(PropertyKeyConst.ENCODE);
if (StringUtils.isBlank(encodeTmp)) {
encode = Constants.ENCODE;
} else {
encode = encodeTmp.trim();
}
initNamespace(properties);
agent = new MetricsHttpAgent(new ServerHttpAgent(properties));
agent.start();
worker = new ClientWorker(agent, configFilterChainManager, properties);
}
MetricsHttpAgent: agent = new MetricsHttpAgent(new ServerHttpAgent(properties));
这里启动只有一个线程的线程池,去securityProxy.login(serverListMgr.getServerUrls());链接nacos服务器。
public ServerHttpAgent(Properties properties) throws NacosException {
serverListMgr = new ServerListManager(properties);
securityProxy = new SecurityProxy(properties);
namespaceId = properties.getProperty(PropertyKeyConst.NAMESPACE);
init(properties);
securityProxy.login(serverListMgr.getServerUrls());
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName("com.alibaba.nacos.client.config.security.updater");
t.setDaemon(true);
return t;
}
});
executorService.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
//如果有userName,即配置了用户名称,进行登录操作,实际是去建立链接(这里是轮询请求。)
securityProxy.login(serverListMgr.getServerUrls());
}
}, 0, securityInfoRefreshIntervalMills, TimeUnit.MILLISECONDS);
}
worker = new ClientWorker(agent, configFilterChainManager, properties);
这里开了两个线程池,
1: 一个线程只有一个线程的线程池(主要处理:checkConfigInfo()这里是定时去拉取新数据,这里暂时不做扩展,后续专门解析这个checkConfigInfo()方法。)
2:还有一个线程数跟CPU核数相等的线程池。
public ClientWorker(final HttpAgent agent, final ConfigFilterChainManager configFilterChainManager, final Properties properties) {
this.agent = agent;
this.configFilterChainManager = configFilterChainManager;
// Initialize the timeout parameter
init(properties);
//单线程池
executor = Executors.newScheduledThreadPool(1, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName("com.alibaba.nacos.client.Worker." + agent.getName());
t.setDaemon(true);
return t;
}
});
//跟CPU核数相等的线程池
executorService = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors(), new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName("com.alibaba.nacos.client.Worker.longPolling." + agent.getName());
t.setDaemon(true);
return t;
}
});
executor.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
try {
checkConfigInfo();
} catch (Throwable e) {
LOGGER.error("[" + agent.getName() + "] [sub-check] rotate check error", e);
}
}
}, 1L, 10L, TimeUnit.MILLISECONDS);
}
d.3: NacosPropertySourceLocator
该Bean是Implements的PropertySourceLocator(这里用到了spring的扩展点,先记着,将springboot启动时会用到这个)
@Order(0)
public class NacosPropertySourceLocator implements PropertySourceLocator
e: NacosConfigAutoConfiguration这个也是自动装配的类
这里面注入了5个Bean:
NacosConfigProperties, //这个上面讲过了
NacosRefreshProperties,//按照类名字,猜测这应该是自动刷新相关的属性
NacosRefreshHistory, //这应该存放历史数据更新的记录,基于内存存放的,最多存放20条历史数据。
NacosConfigManager, //上面也讲过了
NacosContextRefresher//重点, 该类implement ApplicationListener接口,看过spring源码的都知道监听模式,所以这里必然也是在spring启动的时候加入到spring的上下文中的。
这里粗略看下NacosContextRegresher类:
监听的事件是 ApplicationReadyEvent ,所以只要找到spring中发布 ApplicationReadyEvent 事件地方,这里就能跳转进来,
public void onApplicationEvent(ApplicationReadyEvent event) {
// many Spring context
if (this.ready.compareAndSet(false, true)) {
this.registerNacosListenersForApplications();
}
}