Dubbo是怎么一个流程将服务注册到注册中心的呢?
Dubbo 采用全 Spring 配置方式,会监听Spring是否启动完毕,启动完后开始初始化Dubbo容器。
👇下面是以Zookeeper为注册中心的Dubbo服务注册时序图
贴一下主要的几处代码,详细说明可以见官方文档
http://dubbo.apache.org/zh-cn/docs/source_code_guide/export-service.html
RegistryProtocol.java
@Override public <T> Exporter<T> export(final Invoker<T> originInvoker) throws RpcException { // 暴露服务 // export invoker final ExporterChangeableWrapper<T> exporter = doLocalExport(originInvoker); // 获得注册中心 URL URL registryUrl = getRegistryUrl(originInvoker); // 获得注册中心对象 // registry provider final Registry registry = getRegistry(originInvoker); // 获得服务提供者 URL final URL registedProviderUrl = getRegistedProviderUrl(originInvoker); //to judge to delay publish whether or not boolean register = registedProviderUrl.getParameter("register", true); // 向注册中心订阅服务消费者 ProviderConsumerRegTable.registerProvider(originInvoker, registryUrl, registedProviderUrl); // 向注册中心注册服务提供者(自己) if (register) { register(registryUrl, registedProviderUrl); ProviderConsumerRegTable.getProviderWrapper(originInvoker).setReg(true); // // 标记向本地注册表的注册服务提供者,已经注册 } // 使用 OverrideListener 对象,订阅配置规则 // Subscribe the override data // FIXME When the provider subscribes, it will affect the scene : a certain JVM exposes the service and call the same service. Because the subscribed is cached key with the name of the service, it causes the subscription information to cover. // 创建订阅配置规则的 URL final URL overrideSubscribeUrl = getSubscribedOverrideUrl(registedProviderUrl); // 创建 OverrideListener 对象,并添加到 `overrideListeners` 中 final OverrideListener overrideSubscribeListener = new OverrideListener(overrideSubscribeUrl, originInvoker); overrideListeners.put(overrideSubscribeUrl, overrideSubscribeListener); // 向注册中心,发起订阅 registry.subscribe(overrideSubscribeUrl, overrideSubscribeListener); //Ensure that a new exporter instance is returned every time export return new DestroyableExporter<T>(exporter, originInvoker, overrideSubscribeUrl, registedProviderUrl); }
最后会通过zkClient将服务的URL地址注册到ZK
protected void doRegister(URL url) { try { zkClient.create(toUrlPath(url), url.getParameter(Constants.DYNAMIC_KEY, true)); } catch (Throwable e) { throw new RpcException("Failed to register " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e); } }