Dubbo基础篇 服务暴露

完整流程图

Dubbo基础篇 服务暴露流程图.png

一句话概括流程

在SpringIOC容器刷新完毕后 (export方法 ContenxtRefreshEvent),根据配置参数组装成URL,通过 proxyFactory.getInvoker ,利用javassist进行对象代理,封装真正的实现类,然后通过URL参数选择对应的协议进行protocol.export(默认dubbo协议)。在Producer第一次暴露的时候会调用 createServer 来创建 Server(默认NettyServer),然后将 export 得到的 exporter 存入Map(后面处理请求时查找),然后向注册中心注册提供者的信息

具体可以概括为四点

  • 组装URL

  • 创建Invoker代理类,封装真正的实现类

  • 打开NettyServer,通过URL选择对应的协议暴露(产生Exporter对象)

    • Exporter对象中会去构建一个调用过滤链(org.apache.dubbo.rpc.protocol.ProtocolFilterWrapper#buildInvokerChain)

      Dubbo基础篇 调用过滤链.png
  • 向注册中心注册提供者信息

入口关键类 ServiceConfig

入口方法

服务暴露的入口方法
主要做的事情是:扫描ServiceConfig,逐个去进行服务的暴露

private void exportServices() {
    // 遍历service
    configManager.getServices().forEach(sc -> {
        // TODO, compatible with ServiceConfig.export()
        ServiceConfig serviceConfig = (ServiceConfig) sc;
        serviceConfig.setBootstrap(this);
        
        if (exportAsync) {
            ExecutorService executor = executorRepository.getServiceExporterExecutor();
            Future future = executor.submit(() -> {
                sc.export();
                exportedServices.add(sc);
            });
            asyncExportingFutures.add(future);
        } else {
            sc.export();
            exportedServices.add(sc);
        }
    });
}
private void doExportUrls() {
  ServiceRepository repository = ApplicationModel.getServiceRepository();
  ServiceDescriptor serviceDescriptor = repository.registerService(getInterfaceClass());
  // 往内存中添加provider
  repository.registerProvider(
    getUniqueServiceName(),
    ref,
    serviceDescriptor,
    this,
    serviceMetadata
  );

  // 获取当前服务的注册中心URL(支持多注册中心)
  List registryURLs = ConfigValidationUtils.loadRegistries(this, true);

  // 遍历协议,并在每个协议下暴露服务
  for (ProtocolConfig protocolConfig : protocols) {
    String pathKey = URL.buildKey(getContextPath(protocolConfig)
                                  .map(p -> p + "/" + path)
                                  .orElse(path), group, version);
    // In case user specified path, register service one more time to map it to path.
    // 注册dubbo service(放入到map中)
    repository.registerService(pathKey, interfaceClass);
    // TODO, uncomment this line once service key is unified
    serviceMetadata.setServiceKey(pathKey);
    // 暴露(将上面存入的dubbo service,生成invoker,再包装成export暴露)
    doExportUrlsFor1Protocol(protocolConfig, registryURLs);
  }
}

前面有一大段都是在进行URL的组装的,这边就不细讲了,具体的可以看下代码的注释

private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List registryURLs) {
        // ============================== URL组装前的准备 ==============================
        String name = protocolConfig.getName();
        if (StringUtils.isEmpty(name)) {
            name = DUBBO;
        }

        Map map = new HashMap();
        map.put(SIDE_KEY, PROVIDER_SIDE);

        ServiceConfig.appendRuntimeParameters(map);
        AbstractConfig.appendParameters(map, getMetrics());
        AbstractConfig.appendParameters(map, getApplication());
        AbstractConfig.appendParameters(map, getModule());
        // ... 此处省略URL组装前的准备流程
        // ============================== URL组装完成 ==============================
        
        // 构建URL
        URL url = new URL(name, host, port, getContextPath(protocolConfig).map(p -> p + "/" + path).orElse(path), map);
        // url的内容
        // dubbo://10.167.10.19:20880/org.apache.dubbo.demo.DemoService?anyhost=true&application=dubbo-demo-api-provider&bind.ip=10.167.10.19&bind.port=20880&default=true&deprecated=false&dubbo=2.0.2&dynamic=true&generic=false&interface=org.apache.dubbo.demo.DemoService&methods=sayHello,sayHelloAsync&pid=43793&release=&side=provider×tamp=1631080120436

        // You can customize Configurator to append extra parameters
        if (ExtensionLoader.getExtensionLoader(ConfiguratorFactory.class)
                .hasExtension(url.getProtocol())) {
            url = ExtensionLoader.getExtensionLoader(ConfiguratorFactory.class)
                    .getExtension(url.getProtocol()).getConfigurator(url).configure(url);
        }

        String scope = url.getParameter(SCOPE_KEY);
        // don't export when none is configured
        // 如果scope为SCOPE_NONE不暴露服务
        if (!SCOPE_NONE.equalsIgnoreCase(scope)) {

            // export to local if the config is not remote (export to remote only when config is remote)
            // 本地暴露
            if (!SCOPE_REMOTE.equalsIgnoreCase(scope)) {
                // 有一个本地暴露,只所以需要本地暴露是考虑到同一个服务内假如需要调用当前的dubbo接口,则可以直接走jvm内部(injvm),减少网络间的通讯
                // 修改url协议为injvm
                exportLocal(url);
            }
            // export to remote if the config is not local (export to local only when config is local)
            // 远程暴露
            if (!SCOPE_LOCAL.equalsIgnoreCase(scope)) {
                // 注册中心不为空
                if (CollectionUtils.isNotEmpty(registryURLs)) {
                    // 遍历注册中心
                    for (URL registryURL : registryURLs) {
                        //if protocol is only injvm ,not register
                        if (LOCAL_PROTOCOL.equalsIgnoreCase(url.getProtocol())) {
                            continue;
                        }
                        url = url.addParameterIfAbsent(DYNAMIC_KEY, registryURL.getParameter(DYNAMIC_KEY));
                        URL monitorUrl = ConfigValidationUtils.loadMonitor(this, registryURL);
                        if (monitorUrl != null) {
                            url = url.addParameterAndEncoded(MONITOR_KEY, monitorUrl.toFullString());
                        }
                        if (logger.isInfoEnabled()) {
                            if (url.getParameter(REGISTER_KEY, true)) {
                                logger.info("Register dubbo service " + interfaceClass.getName() + " url " + url + " to registry " + registryURL);
                            } else {
                                logger.info("Export dubbo service " + interfaceClass.getName() + " to url " + url);
                            }
                        }

                        // For providers, this is used to enable custom proxy to generate invoker
                        String proxy = url.getParameter(PROXY_KEY);
                        if (StringUtils.isNotEmpty(proxy)) {
                            registryURL = registryURL.addParameter(PROXY_KEY, proxy);
                        }

                        // 生成Invoker对象(动态代理创建 javassist)
                        Invoker invoker = PROXY_FACTORY.getInvoker(ref, (Class) interfaceClass, registryURL.addParameterAndEncoded(EXPORT_KEY, url.toFullString()));
                        // 包装
                        DelegateProviderMetaDataInvoker wrapperInvoker = new DelegateProviderMetaDataInvoker(invoker, this);

                        // provider 需要将 invoker 封装成 expoter(并在此处进行注册)
                        Exporter exporter = PROTOCOL.export(wrapperInvoker);
                        exporters.add(exporter);
                    }
                } else {
                    // 直连方式
                    if (logger.isInfoEnabled()) {
                        logger.info("Export dubbo service " + interfaceClass.getName() + " to url " + url);
                    }
                    Invoker invoker = PROXY_FACTORY.getInvoker(ref, (Class) interfaceClass, url);
                    DelegateProviderMetaDataInvoker wrapperInvoker = new DelegateProviderMetaDataInvoker(invoker, this);

                    Exporter exporter = PROTOCOL.export(wrapperInvoker);
                    exporters.add(exporter);
                }

                // 元数据存储
                MetadataUtils.publishServiceDefinition(url);
            }
        }
        this.urls.add(url);
    }

默认情况下 ,我们的scope为null,他会进行本地暴露+远程暴露
那么从上面的代码我们可以看出,主要是做了两件事情:

  • URL的组装
  • 本地暴露+远程暴露

为什么需要本地暴露呢?

因为有可能会存在自己的服务调用自己暴露的接口的情况,假如这种情况还走远程调用的话,效率肯定没有jvm内部的本地调用高

生成Invoker对象

Invoker invoker = PROXY_FACTORY.getInvoker(ref, (Class) interfaceClass, registryURL.addParameterAndEncoded(EXPORT_KEY, url.toFullString()));

以Javassist为例(默认为Javassist)

@Override
public  Invoker getInvoker(T proxy, Class type, URL url) {
    // TODO Wrapper cannot handle this scenario correctly: the classname contains '$'
    // 通过Javaassist封装成Wrapper类(Dubbo服务启动时生成,所以在运行时不会产生开销),减少反射的调用
        // Wrapper.getWrapper -> 反射获取对应的类信息,包装成Wrapper对象
    final Wrapper wrapper = Wrapper.getWrapper(proxy.getClass().getName().indexOf('$') < 0 ? proxy.getClass() : type);
    return new AbstractProxyInvoker(proxy, type, url) {
        @Override
        // Wrapper最终调用最终调用服务提供者的接口实现类的方法
        protected Object doInvoke(T proxy, String methodName,
                                  Class[] parameterTypes,
                                  Object[] arguments) throws Throwable {
            return wrapper.invokeMethod(proxy, methodName, parameterTypes, arguments);
        }
    };
}

为什么需要Wrapper类修饰

目的:减少反射调用的开销


Dubbo基础篇 为什么需要Wrapper类修饰1.png

Dubbo基础篇 为什么需要Wrapper类修饰2.png

暴露操作

Exporter exporter = PROTOCOL.export(wrapperInvoker)

关于此处重点看两个类

RegisterProtocol

@Override
public  Exporter export(final Invoker originInvoker) throws RpcException {
    // 获取注册中心URL
    URL registryUrl = getRegistryUrl(originInvoker);
    // url to export locally
    // 获取提供者URL
    URL providerUrl = getProviderUrl(originInvoker);

    // 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.
    final URL overrideSubscribeUrl = getSubscribedOverrideUrl(providerUrl);
    final OverrideListener overrideSubscribeListener = new OverrideListener(overrideSubscribeUrl, originInvoker);
    overrideListeners.put(overrideSubscribeUrl, overrideSubscribeListener);

    providerUrl = overrideUrlWithConfig(providerUrl, overrideSubscribeListener);
    //export invoker
    // 选择具体的协议去暴露服务
    // 以DubboProtocol为例,最终调用到DubboProtocol
    final ExporterChangeableWrapper exporter = doLocalExport(originInvoker, providerUrl);

    // url to registry
    // 获取注册中心
    final Registry registry = getRegistry(originInvoker);
    final URL registeredProviderUrl = getUrlToRegistry(providerUrl, registryUrl);

    // decide if we need to delay publish
    boolean register = providerUrl.getParameter(REGISTER_KEY, true);
    if (register) {
        // 注册服务
        register(registryUrl, registeredProviderUrl);
    }

    // register stated url on provider model
    registerStatedUrl(registryUrl, registeredProviderUrl, register);


    exporter.setRegisterUrl(registeredProviderUrl);
    exporter.setSubscribeUrl(overrideSubscribeUrl);

    // Deprecated! Subscribe to override rules in 2.6.x or before.
    // 订阅
    registry.subscribe(overrideSubscribeUrl, overrideSubscribeListener);

    notifyExport(exporter);
    //Ensure that a new exporter instance is returned every time export
    return new DestroyableExporter<>(exporter);
}

DubboProtocol

@Override
public  Exporter export(Invoker invoker) throws RpcException {
    URL url = invoker.getUrl();

    // export service.
    // 创建ServiceKey
    String key = serviceKey(url);
    // 将上层传入的Invoker对象封装成DubboExporter对象,然后记录到exporterMap集合中
    DubboExporter exporter = new DubboExporter(invoker, key, exporterMap);
    exporterMap.put(key, exporter);

    //export an stub service for dispatching event
    Boolean isStubSupportEvent = url.getParameter(STUB_EVENT_KEY, DEFAULT_STUB_EVENT);
    Boolean isCallbackservice = url.getParameter(IS_CALLBACK_SERVICE, false);
    if (isStubSupportEvent && !isCallbackservice) {
        String stubServiceMethods = url.getParameter(STUB_EVENT_METHODS_KEY);
        if (stubServiceMethods == null || stubServiceMethods.length() == 0) {
            if (logger.isWarnEnabled()) {
                logger.warn(new IllegalStateException("consumer [" + url.getParameter(INTERFACE_KEY) +
                        "], has set stubproxy support event ,but no stub methods founded."));
            }

        }
    }

    // 启动ProtocolServer
    openServer(url);
    // 进行序列化的优化处理
    optimizeSerialization(url);

    return exporter;
}

打开一个服务

以当前的机器的(ip:port)为key,查看缓存中是否存在Server,没有则创建一个
不同协议暴露的端口不同,例如http协议可以选择8080端口之类的,dubbo协议为20880
默认 NettyServer

private ProtocolServer createServer(URL url) {
  url = URLBuilder.from(url)
          // send readonly event when server closes, it's enabled by default
          // readonlty请求是否阻塞等待
          .addParameterIfAbsent(CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString())
          // enable heartbeat by default
          // 心跳间隔
          .addParameterIfAbsent(HEARTBEAT_KEY, String.valueOf(DEFAULT_HEARTBEAT))
          // Codec2扩展实现
          .addParameter(CODEC_KEY, DubboCodec.NAME)
          .build();
  // 检测SERVER_KEY参数指定的Transporter扩展实现是否合法
  String str = url.getParameter(SERVER_KEY, DEFAULT_REMOTING_SERVER);

  if (str != null && str.length() > 0 && !ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str)) {
      throw new RpcException("Unsupported server type: " + str + ", url: " + url);
  }

  ExchangeServer server;
  try {
      // 通过Exchangers门面类,创建ExchangeServer对象
      // 处理consumer的请求
            // handler -> 对应netty的handler
      server = Exchangers.bind(url, requestHandler);
  } catch (RemotingException e) {
      throw new RpcException("Fail to start server(url: " + url + ") " + e.getMessage(), e);
  }

  // 检测CLIENT_KEY参数指定的Transporter扩展实现是否合法
  str = url.getParameter(CLIENT_KEY);
  if (str != null && str.length() > 0) {
      Set supportedTypes = ExtensionLoader.getExtensionLoader(Transporter.class).getSupportedExtensions();
      if (!supportedTypes.contains(str)) {
          throw new RpcException("Unsupported client type: " + str);
      }
  }

  // 将ExchangeServer封装成DubboProtocolServer返回
  return new DubboProtocolServer(server);
}

注册到注册中心

@Override
public Registry getRegistry(URL url) {
    if (destroyed.get()) {
        LOGGER.warn("All registry instances have been destroyed, failed to fetch any instance. " +
                "Usually, this means no need to try to do unnecessary redundant resource clearance, all registries has been taken care of.");
        return DEFAULT_NOP_REGISTRY;
    }

    url = URLBuilder.from(url)
            .setPath(RegistryService.class.getName())
            .addParameter(INTERFACE_KEY, RegistryService.class.getName())
            .removeParameters(EXPORT_KEY, REFER_KEY)
            .build();
    String key = createRegistryCacheKey(url);
    // Lock the registry access process to ensure a single instance of the registry
    LOCK.lock();
    try {
        Registry registry = REGISTRIES.get(key);
        if (registry != null) {
            return registry;
        }
        //create registry by spi/ioc
                // 创建注册中心实例
        registry = createRegistry(url);
        if (registry == null) {
            throw new IllegalStateException("Can not create registry " + url);
        }
        REGISTRIES.put(key, registry);
        return registry;
    } finally {
        // Release the lock
        LOCK.unlock();
    }
}
@Override
public void register(URL url) {
        // 注册服务
    this.register(new com.alibaba.dubbo.common.URL(url));
}

你可能感兴趣的:(Dubbo基础篇 服务暴露)