Nacos - 启动提到了NacosWatch#start会获取NamingService,他托管NacosServiceManager来完成这件事。segmentfault
为空的时候,去建立一个NamingService缓存
public NamingService getNamingService(Properties properties) { // 为空的时候,去建立一个NamingService if (Objects.isNull(this.namingService)) { buildNamingService(properties); } // 返回namingService return namingService; }
加锁保证只能有一个namingServiceui
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对象。this
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); }
经过反射的方式建立了com.alibaba.nacos.client.naming.NacosNamingService对象。spa
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); } }
主要是初始化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)); }