在dubbo之服务本地暴露 文章中,我们分析了当scope="local"时使用injvm协议的本地服务注册,本文一起来看下实际业务中最常使用的方式,即远端服务暴露,相比于本地暴露,主要是多做如下的几件事:
1:启动通信服务器,绑定服务端口,准备接收服务消费者端的远程请求。2:注册服务端口信息到注册中心,供服务消费者获取服务调用信息。
下面我们就开始吧!
在dubbo之服务本地暴露 文章基础上从doExportUrlsFor1Protocol,具体参考1.1:doExportUrlsFor1Protocol。
1:远程暴漏时序图如下:
1.1:doExportUrlsFor1Protocol源码如下:
// com.alibaba.dubbo.config.ServiceConfig.doExportUrlsFor1Protocolclass FakeCls { private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List
2022-01-31 15:01:03处是完成服务的暴漏,在dubbo之服务本地暴露 一文中我们知道Protocol是使用了Wrapper 的自适应扩展类 ,因此在调用真正的Protocol实现类之前,会先调用自动生成的Adaptive类,以及所有的Wrapper类,如下debug图:
以上调用顺序的原因是,保证服务启动后在向注册中心注册服务启动信息,如下伪代码:
class RegistryProtocol { void export() { // 使用DubboProtocol暴漏服务,即启动netty,监听服务端口 new DubboProtocol().export(); // 完成服务启动后,将服务信息注册到注册中心 registerServerInfo(); }}
详细的我们在2:Protocol一起看下。
2:Protocol 2.1:ProtocolFilterWrapper源码如下:
class FakeCls { public
2022-01-31 16:30:07处是使用RegistryProtocol暴漏服务,因此这个方法主要做了如下的两件事:
1:注册服务到注册中心 启动本地接收远程调用服务->注册服务信息到注册中心2:暴漏服务
具体参考2.2:RegistryProtocol。
2.2:RegistryProtocol源码如下:
class FakeCls { public
2022-01-31 16:58:42处是暴漏服务具体参考2.2.1:doLocalExport。2022-02-06 16:46:37处是获取注册中心的地址,因为需要将服务注册到注册中心了,所以这里开始获取注册中心地址,具体参考2.2.2:getRegistryUrl。2022-02-07 11:16:00处是向本地注册表中注册服务,具体参考4:ProviderConsumerRegTable。2022-02-07 13:05:06处是注册服务地址到注册中心,具体参考2.2.3:register。
2.2.1:doLocalExport 该方法只是本地启动服务,而不会向注册中心注册服务。
源码如下:
class FakeCls { private
2022-01-31 17:33:00处是获取bounds的缓存key,具体参考2.2.1.1:getCacheKey。2022-02-01 11:31:59处是执行DCL检查 ,防止进入同步的条件发生改变。2022-02-01 17:11:26处的protocol.export(invokerDelegete)我们来分析下,其中protocol是Protocol$Adaptive,在dubbo之服务本地暴露 文章中我们分析了Protocol$Adaptive动态生成的代码如下:
public class Protocol$Adaptive implements com.alibaba.dubbo.rpc.Protocol { public void destroy() { throw new UnsupportedOperationException("method public abstract void com.alibaba.dubbo.rpc.Protocol.destroy() of interface com.alibaba.dubbo.rpc.Protocol is not adaptive method!"); } public int getDefaultPort() { throw new UnsupportedOperationException("method public abstract int com.alibaba.dubbo.rpc.Protocol.getDefaultPort() of interface com.alibaba.dubbo.rpc.Protocol is not adaptive method!"); } public com.alibaba.dubbo.rpc.Invoker refer(java.lang.Class arg0, com.alibaba.dubbo.common.URL arg1) throws com.alibaba.dubbo.rpc.RpcException { if (arg1 == null) throw new IllegalArgumentException("url == null"); com.alibaba.dubbo.common.URL url = arg1; String extName = (url.getProtocol() == null ? "dubbo" : url.getProtocol()); if (extName == null) throw new IllegalStateException("Fail to get extension(com.alibaba.dubbo.rpc.Protocol) name from url(" + url.toString() + ") use keys([protocol])"); com.alibaba.dubbo.rpc.Protocol extension = (com.alibaba.dubbo.rpc.Protocol) ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.rpc.Protocol.class).getExtension(extName); return extension.refer(arg0, arg1); } public com.alibaba.dubbo.rpc.Exporter export(com.alibaba.dubbo.rpc.Invoker arg0) throws com.alibaba.dubbo.rpc.RpcException { if (arg0 == null) throw new IllegalArgumentException("com.alibaba.dubbo.rpc.Invoker argument == null"); if (arg0.getUrl() == null) throw new IllegalArgumentException("com.alibaba.dubbo.rpc.Invoker argument getUrl() == null"); com.alibaba.dubbo.common.URL url = arg0.getUrl(); String extName = (url.getProtocol() == null ? "dubbo" : url.getProtocol()); if (extName == null) throw new IllegalStateException("Fail to get extension(com.alibaba.dubbo.rpc.Protocol) name from url(" + url.toString() + ") use keys([protocol])"); com.alibaba.dubbo.rpc.Protocol extension = (com.alibaba.dubbo.rpc.Protocol) ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.rpc.Protocol.class).getExtension(extName); return extension.export(arg0); }}
我们注意export方法中的代码String extName = (url.getProtocol() == null ? "dubbo" : url.getProtocol());,根据协议来获取目标扩展名称,此时debug可以看到结果如下:
结果是dubbo,再考虑Wrapper 的情况,因此最终的调用顺序是ProtocolAdaptive->ProtocolListenerWrapper->PotocolFilterWrapper->DubboProtocol,具体调用过程参考3:DubboProtocol。
2.2.1.1:getCacheKey源码如下:
class FakeCls { private String getCacheKey(final Invoker<?> originInvoker) { // 2022-01-31 17:38:19 // 获取服务提供者地址 URL providerUrl = getProviderUrl(originInvoker); // 删除dynamic,enabled,然后转成字符串作为缓存键,结果如: // dubbo://192.168.2.107:20826/dongshi.daddy.service.monitor.DubboMonitorService... String key = providerUrl.removeParameters("dynamic", "enabled").toFullString(); return key; }}
2022-01-31 17:38:19处是获取服务提供者的URL,源码如下:
class FakeCls { private URL getProviderUrl(final Invoker<?> origininvoker) { // 值在2022-01-31 17:39:34处已经设置,所以这里可以直接获取 // 如:registry://127.0.0.1:2181/com.alibaba.dubbo.registry.RegistryService?...&export= // 获取的结果是:dubbo%3A%2F%2F192.168.2.107%3A20826%2Fdongshi.daddy.service.monitor.DubboMonitorService String export = origininvoker.getUrl().getParameterAndDecoded(Constants.EXPORT_KEY); // 这里必须有export,不然抛出java.lang.IllegalArgumentException异常 if (export == null || export.length() == 0) { throw new IllegalArgumentException("The registry export url is null! registry: " + origininvoker.getUrl()); } // 转成com.alibaba.dubbo.common.URL对象 URL providerUrl = URL.valueOf(export); return providerUrl; }}
2.2.2:getRegistryUrl源码如下:
class FakeCls { // com.alibaba.dubbo.registry.integration.RegistryProtocol.getRegistryUrl private URL getRegistryUrl(Invoker<?> originInvoker) { // 直接获取注册中心地址,如:registry://127.0.0.1:2181/com.alibaba.dubbo.registry.RegistryService?... URL registryUrl = originInvoker.getUrl(); // 如果是"public static final String REGISTRY_PROTOCOL = "registry";"协议,即registry:// if (Constants.REGISTRY_PROTOCOL.equals(registryUrl.getProtocol())) { // 获取registry参数的值作为新的协议名称,如我本地使用zk,是registry://127.0.0.1:2181/com.alibaba.dubbo.registry.RegistryService?...®istry=zookeeper... // 结果就是zookeeper String protocol = registryUrl.getParameter(Constants.REGISTRY_KEY, Constants.DEFAULT_DIRECTORY); // 使用zookeeper作为新的协议名称,registry://127.0.0.1:2181..、-> zookeeper://127.0.0.1:2181... registryUrl = registryUrl.setProtocol(protocol).removeParameter(Constants.REGISTRY_KEY); } // 结果如:zookeeper://127.0.0.1:2181/com.alibaba.dubbo.registry.RegistryService?... return registryUrl; }}
2.2.3:register源码如下:
class FakeCls { // com.alibaba.dubbo.registry.integration.RegistryProtocol.register public void register(URL registryUrl, URL registedProviderUrl) { // 2022-02-07 14:17:03 Registry registry = registryFactory.getRegistry(registryUrl); // 2022-02-07 15:51:34 // 使用zk作为注册中心的话,这里获取的是com.alibaba.dubbo.registry.zookeeper.ZookeeperRegistry registry.register(registedProviderUrl); }}
2022-02-07 14:17:03处是通过RegistryFactory获取Registry,其中RegistryFactory是一个自适应 的扩展接口,registryFactory是自动生成的自适应扩展类RegistryFactory$Adaptive。
RegistryFactory源码如下:
@SPI("dubbo")public interface RegistryFactory { @Adaptive({"protocol"}) Registry getRegistry(URL url);}
自动生成代码如下:
package com.alibaba.dubbo.registry;import com.alibaba.dubbo.common.extension.ExtensionLoader;public class RegistryFactory$Adaptive implements com.alibaba.dubbo.registry.RegistryFactory {public com.alibaba.dubbo.registry.Registry getRegistry(com.alibaba.dubbo.common.URL arg0) {if (arg0 == null) throw new IllegalArgumentException("url == null");com.alibaba.dubbo.common.URL url = arg0;String extName = ( url.getProtocol() == null ? "dubbo" : url.getProtocol() );if(extName == null) throw new IllegalStateException("Fail to get extension(com.alibaba.dubbo.registry.RegistryFactory) name from url(" + url.toString() + ") use keys([protocol])");com.alibaba.dubbo.registry.RegistryFactory extension = (com.alibaba.dubbo.registry.RegistryFactory)ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.registry.RegistryFactory.class).getExtension(extName);return extension.getRegistry(arg0);}}
执行代码String extName = ( url.getProtocol() == null ? "dubbo" : url.getProtocol() );,获取的结果是extName=zookeeper,那么对应的是哪个扩展类呢,可以从meta-INFdubbointernalcom.alibaba.dubbo.registry.RegistryFactory文件找到答案,内容如下:
dubbo=com.alibaba.dubbo.registry.dubbo.DubboRegistryFactorymulticast=com.alibaba.dubbo.registry.multicast.MulticastRegistryFactoryzookeeper=com.alibaba.dubbo.registry.zookeeper.ZookeeperRegistryFactoryredis=com.alibaba.dubbo.registry.redis.RedisRegistryFactory
最终获取到的扩展类就是ZookeeperRegistryFactory,会调用其getRegistry,因为该方法是在其父类AbstractRegistryFactory中定义的,因此最终调用的方法如下:
class FakeCls { // com.alibaba.dubbo.registry.support.AbstractRegistryFactory.getRegistry public Registry getRegistry(URL url) { // 1:设置路径为com.alibaba.dubbo.registry.RegistryService // 2:设置参数interface=com.alibaba.dubbo.registry.RegistryService // 3:删除参数export url = url.setPath(RegistryService.class.getName()) .addParameter(Constants.INTERFACE_KEY, RegistryService.class.getName()) .removeParameters(Constants.EXPORT_KEY, Constants.REFER_KEY); // 缓存键,如zookeeper://127.0.0.1:2181/com.alibaba.dubbo.registry.RegistryService String key = url.toServiceString(); LOCK.lock(); try { // 缓存获取 Registry registry = REGISTRIES.get(key); // 缓存有,直接return if (registry != null) { return registry; } // 2022-02-07 14:58:54 registry = createRegistry(url); // 不能拿不到 if (registry == null) { throw new IllegalStateException("Can not create registry " + url); } // 放入缓存 REGISTRIES.put(key, registry); return registry; } finally { LOCK.unlock(); } }}
2022-02-07 14:58:54处是创建Registry,具体参考2.2.4:createRegistry。2022-02-07 15:51:34处是通过对应注册中心的Registry注册服务提供者的url,具体参考2.2.5:注册服务地址到注册中心。
2.2.4:createRegistry源码如下:
class FakeCls { // com.alibaba.dubbo.registry.support.AbstractRegistryFactory.createRegistry protected abstract Registry createRegistry(URL url);}
我们发现这是一个抽象的模板方法,具体调用的是com.alibaba.dubbo.registry.zookeeper.ZookeeperRegistryFactory.createRegistry,源码如下:
class FakeCls { // com.alibaba.dubbo.registry.zookeeper.ZookeeperRegistryFactory.createRegistry public Registry createRegistry(URL url) { // 直接new ZookeeperRegistry返回 return new ZookeeperRegistry(url, zookeeperTransporter); }}
ZookeeperRegistry构造函数如下:
class FakeCls { // com.alibaba.dubbo.registry.zookeeper.ZookeeperRegistry.ZookeeperRegistry public ZookeeperRegistry(URL url, ZookeeperTransporter zookeeperTransporter) { super(url); if (url.isAnyHost()) { throw new IllegalStateException("registry address == null"); } // dubbo String group = url.getParameter(Constants.GROUP_KEY, DEFAULT_ROOT); // /dubbo if (!group.startsWith(Constants.PATH_SEPARATOR)) { group = Constants.PATH_SEPARATOR + group; } this.root = group; // 获取操作zk的客户端对象 zkClient = zookeeperTransporter.connect(url); // 增加状态变化监听器 zkClient.addStateListener(new StateListener() { @Override public void stateChanged(int state) { if (state == RECONNECTED) { try { recover(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } }); }}
2.2.5:注册服务地址到注册中心我们这里以ZookeeperRegistry为例来说明,源码如下:
class FakeCls { // com.alibaba.dubbo.registry.zookeeper.ZookeeperRegistry.doRegister protected void doRegister(URL url) { try { // toUrlPath(url):要创建的zk路径,如/dubbo/dongshi.daddy.service.monitor.DubboMonitorService/providers/dubbo...version%3D0.0.11 // 执行后,对应的路径在zk就建立完毕,服务信息注册到注册中心,消费者可以通过注册中心获取服务提供者的信息了 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); } }}
3:DubboProtocol源码如下:
class FakeCls { public
2022-02-01 18:58:33处是生成服务的唯一标识,具体参考3.1:serviceKey。2022-02-02 10:10:53处是启动服务器,具体参考3.2:openServer。
3.1:serviceKey源码如下:
class FakeCls { protected static String serviceKey(URL url) { // 获取要绑定的端口,public static final String BIND_PORT_KEY = "bind.port"; // dubbo://192.168.2.107:20826/dongshi.daddy.service.monitor.DubboMonitorService,结果是20826 int port = url.getParameter(Constants.BIND_PORT_KEY, url.getPort()); // port:20826, // url.getPath(): dongshi.daddy.service.monitor.DubboMonitorService // url.getParameter(Constants.VERSION_KEY):如
2022-02-01 19:51:29处最终调用到方法com.alibaba.dubbo.rpc.support.ProtocolUtils.serviceKey(int, java.lang.String, java.lang.String, java.lang.String)源码如下:
class FakeCls { // com.alibaba.dubbo.rpc.support.ProtocolUtils.serviceKey(int, java.lang.String, java.lang.String, java.lang.String) public static String serviceKey(int port, String serviceName, String serviceVersion, String serviceGroup) { StringBuilder buf = new StringBuilder(); // 组名称/ if (serviceGroup != null && serviceGroup.length() > 0) { buf.append(serviceGroup); buf.append("/"); } // 组名称/服务名称 buf.append(serviceName); // 组名称/服务名称:版本号 if (serviceVersion != null && serviceVersion.length() > 0 && !"0.0.0".equals(serviceVersion)) { buf.append(":"); buf.append(serviceVersion); } // 组名称/服务名称:版本号:端口号 buf.append(":"); buf.append(port); // 结果如:xxxx/dongshi.daddy.service.monitor.DubboMonitorService:0.0.11:20826 return buf.toString(); }}
3.2:openServer源码如下:
class FakeCls { private void openServer(URL url) { // 使用地址作为唯一标识,如192.168.2.107:20826 String key = url.getAddress(); // url正常无该值,而默认值是true,所以这里可以认为是true boolean isServer = url.getParameter(Constants.IS_SERVER_KEY, true); if (isServer) { // ExchangeServer代表了服务器,是Server接口的子接口 // Map
2022-02-05 20:26:00处是利用URL创建Server并添加到serverMap中,具体参考3.3:createServer。
3.3:createServer源码如下:
class FakeCls { private ExchangeServer createServer(URL url) { // public static final String CHANNEL_READONLYEVENT_SENT_KEY = "channel.readonly.sent"; // server关闭时发送READONLY事件 // dubbo://192.168.2.107:20826/dongshi.daddy.service.monitor.DubboMonitorService?...&channel.readonly.sent=true&... url = url.addParameterIfAbsent(Constants.CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString()); // public static final int DEFAULT_HEARTBEAT = 60 * 1000; // public static final String HEARTBEAT_KEY = "heartbeat"; // 启用心跳,默认心跳时长一分钟 // dubbo://192.168.2.107:20826/dongshi.daddy.service.monitor.DubboMonitorService?...&heartbeat=60000&... url = url.addParameterIfAbsent(Constants.HEARTBEAT_KEY, String.valueOf(Constants.DEFAULT_HEARTBEAT)); // public static final String SERVER_KEY = "server"; // public static final String DEFAULT_REMOTING_SERVER = "netty"; // 检验是否有对应名称的Transporter Dubbo SPI扩展类,Transporter是用于操作netty,mina等框架的接口 String str = url.getParameter(Constants.SERVER_KEY, Constants.DEFAULT_REMOTING_SERVER); // 保证对应的扩展类存在 if (str != null && str.length() > 0 && !ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str)) throw new RpcException("Unsupported server type: " + str + ", url: " + url); // 使用dubbo codec编解码,即DubboCountCodec url = url.addParameter(Constants.CODEC_KEY, DubboCodec.NAME); ExchangeServer server; try { // 2022-02-06 12:45:27 server = Exchangers.bind(url, requestHandler); } catch (RemotingException e) { throw new RpcException("Fail to start server(url: " + url + ") " + e.getMessage(), e); } // 检验client扩展类必须存在 str = url.getParameter(Constants.CLIENT_KEY); if (str != null && str.length() > 0) { Set
2022-02-06 12:45:27处Exchangers是Exchanger的门面类 ,用来封装底层系统的细节,简化用户的使用,最后返回的是ExchangeServer,这是Server的一个子接口,定义如下:
public interface ExchangeServer extends Server { Collection
bind方法执行输出的日志如下:
[2022-02-0613:06:28][INFO ][jpm-AbstractServer-
可以看出来是启动了netty服务,并暴漏服务端口了。
4:ProviderConsumerRegTable该类是用于进行本地服务消费者和服务提供者注册的支持类(工具类),为了了服务提供者和服务消费者的Invoker,主要用于进行QOS(quality of service),如上下线,统计等,相关代码如下:
public class ProviderConsumerRegTable { public static ConcurrentHashMap
provider invoker的wrapper类,主要是增加了一些额外的辅助运维属性,比如标记是否注册的属性isReg,当进行下线操作后就可以修改为false,代表已经下线,主要属性如下:
class FakeCls { private Invoker
consumer invoker的wrapper类,主要是增加了一些额外的属性,如下:
class FakeCls { private Invoker