Nacos - 启动提到了NacosWatch#start会获取NamingService,他托管NacosServiceManager来实现这件事。
NacosServiceManager#getNamingService
为空的时候,去创立一个NamingService
public NamingService getNamingService(Properties properties) { // 为空的时候,去创立一个NamingService if (Objects.isNull(this.namingService)) { buildNamingService(properties); } // 返回namingService return namingService;}
NacosServiceManager#buildNamingService
加锁保障只能有一个namingService
private NamingService buildNamingService(Properties properties) { if (Objects.isNull(namingService)) { // 加锁保障只能有一个namingService synchronized (NacosServiceManager.class) { if (Objects.isNull(namingService)) { namingService = createNewNamingService(properties); } } } return namingService;}
最终调用NamingFactory#createNamingService来创立NamingService对象。
private NamingService createNewNamingService(Properties properties) { try { return createNamingService(properties); } catch (NacosException e) { throw new RuntimeException(e); }}// NacosFactory中的办法public static NamingService createNamingService(Properties properties) throws NacosException { return NamingFactory.createNamingService(properties);}
NamingFactory#createNamingService
通过反射的形式创立了com.alibaba.nacos.client.naming.NacosNamingService对象。
public static NamingService createNamingService(String serverList) throws NacosException { try { Class<?> driverImplClass = Class.forName("com.alibaba.nacos.client.naming.NacosNamingService"); Constructor constructor = driverImplClass.getConstructor(String.class); NamingService vendorImpl = (NamingService) constructor.newInstance(serverList); return vendorImpl; } catch (Throwable e) { throw new NacosException(NacosException.CLIENT_INVALID_PARAM, e); }}
NacosNamingService#init
次要是初始化namespace、序列化、注册核心服务地址、WebRootContext上下文、缓存门路、日志名称、EventDispatcher、NamingProxy、BeatReactor、HostReactor。
EventDispatcher负责解决服务监听相干。
NamingProxy负责和Nacos服务的通信,比方服务注册、服务勾销注册、心跳等。
BeatReactor负责检测心跳。
HostReactor负责获取、更新并保留服务信息。
private void init(Properties properties) throws NacosException { ValidatorUtils.checkInitParam(properties); // namespace默认public this.namespace = InitUtils.initNamespaceForNaming(properties); // 序列化初始化 InitUtils.initSerialization(); // 注册核心服务地址初始化,这个从配置文件取 initServerAddr(properties); //初始化WebRootContext上下文 InitUtils.initWebRootContext(); // 初始化缓存门路 System.getProperty("user.home") + "/nacos/naming/" + namespace initCacheDir(); // 初始化日志名称naming.log initLogName(properties); // 初始化EventDispatcher this.eventDispatcher = new EventDispatcher(); // 初始化NamingProxy this.serverProxy = new NamingProxy(this.namespace, this.endpoint, this.serverList, properties); // 初始化BeatReactor this.beatReactor = new BeatReactor(this.serverProxy, initClientBeatThreadCount(properties)); // 初始化HostReactor this.hostReactor = new HostReactor(this.eventDispatcher, this.serverProxy, beatReactor, this.cacheDir, isLoadCacheAtStart(properties), initPollingThreadCount(properties));}