1、Dubbo服务引入简介

前两篇文章 Dubbo的服务导出1之导出到本地、Dubbo的服务导出2之导出到远程 详细分析了服务导出的过程,本篇文章我们趁热打铁,继续分析服务引用过程。在 Dubbo 中,我们可以通过两种方式引用远程服务。第一种是使用服务直连的方式引用服务,第二种方式是基于注册中心进行引用。服务直连的方式仅适合在调试或测试服务的场景下使用,不适合在线上环境使用。因此,本文我将重点分析通过注册中心引用服务的过程。从注册中心中获取服务配置只是服务引用过程中的一环,除此之外,服务消费者还需要经历 Invoker 创建、代理类创建等步骤。这些步骤,将在后续章节中一一进行分析。

2、服务引用原理

Dubbo 服务引用的时机有两个,第一个是在Spring 容器调用 ReferenceBean的afterPropertiesSet方法时引用服务,第二个是在 ReferenceBean对应的服务被注入到其他类中时引用。这两个引用服务的时机区别在于,第一个是饿汉式的,第二个是懒汉式的。默认情况下,Dubbo使用懒汉式引用服务。如果需要使用饿汉式,可通过配置 <dubbo:reference> 的 init 属性开启。下面我们按照 Dubbo 默认配置进行分析,整个分析过程从 ReferenceBean 的 getObject 方法开始。当我们的服务被注入到其他类中时,Spring 会第一时间调用 getObject 方法,并由该方法执行服务引用逻辑。按照惯例,在进行具体工作之前,需先进行配置检查与收集工作。接着根据收集到的信息决定服务用的方式,有三种,第一种是引用本地 (JVM) 服务,第二是通过直连方式引用远程服务,第三是通过注册中心引用远程服务。不管是哪种引用方式,最后都会得到一个 Invoker 实例。如果有多个注册中心,多个服务提供者,这个时候会得到一组 Invoker 实例,此时需要通过集群管理类 Cluster 将多个 Invoker 合并成一个实例。合并后的 Invoker 实例已经具备调用本地或远程服务的能力了,但并不能将此实例暴露给用户使用,这会对用户业务代码造成侵入。此时框架还需要通过代理工厂类 (ProxyFactory) 为服务接口生成代理类,并让代理类去调用 Invoker 逻辑。避免了 Dubbo 框架代码对业务代码的侵入,同时也让框架更容易使用。
以上就是服务引用的大致原理,下面我们深入到代码中,详细分析服务引用细节。

3、源码分析

3.1、配置检查与收集

// ReferenceBean实现了InitializingBean接口,因此在Spring容器初始化时会调用该方法,这里也对应上述第一个引用时机// 默认不会走这里的引用服务方法,需要配置init=true@Overridepublic void afterPropertiesSet() throws Exception {    // 删除一些代码        // Dubbo服务引用的时机有两个,第一个是在Spring容器调用ReferenceBean的afterPropertiesSet    // 方法时引用服务,第二个是在ReferenceBean对应的服务被注入到其他类中时引用.这两个引用服务的时机    // 区别在于,第一个是饿汉式的,第二个是懒汉式的.默认情况下,Dubbo使用懒汉式引用服务.如果需要使用    // 饿汉式,可通过配置<dubbo:reference>的init属性开启.    Boolean b = isInit();    if (b == null && getConsumer() != null) {        b = getConsumer().isInit();    }    if (b != null && b.booleanValue()) {        getObject();    }}
/** * 整个分析过程从ReferenceBean的getObject方法开始.当我们的服务被注入到其他类中时, * Spring会第一时间调用getObject方法,并由该方法执行服务引用逻辑 */@Overridepublic Object getObject() throws Exception {    return get();}public synchronized T get() {    if (destroyed) {        throw new IllegalStateException("Already destroyed!");    }    // 检测ref是否为空,为空则通过init方法创建    if (ref == null) {        // init方法主要用于处理配置,以及调用createProxy生成代理类        init();    }    return ref;}

init方法比较长,为了排版,分成几段,并删除异常捕捉、日志记录等代码,核心代码是ref = createProxy(map)

private void init() {    // 避免重复初始化    if (initialized) {        return;    }    initialized = true;    // 检查接口合法性    if (interfaceName == null || interfaceName.length() == 0) {        throw new IllegalStateException("xxx");    }    // 获取consumer的全局配置    checkDefault();    appendProperties(this);    if (getGeneric() == null && getConsumer() != null) {        setGeneric(getConsumer().getGeneric());    }
    // 检测是否为泛化接口    if (ProtocolUtils.isGeneric(getGeneric())) {        interfaceClass = GenericService.class;    } else {        try {            // 加载类            interfaceClass = Class.forName(interfaceName, true, Thread.currentThread()                    .getContextClassLoader());        } catch (ClassNotFoundException e) {            throw new IllegalStateException(e.getMessage(), e);        }        checkInterfaceAndMethods(interfaceClass, methods);    }
    // 从系统变量中获取与接口名对应的属性值    String resolve = System.getProperty(interfaceName);    String resolveFile = null;    if (resolve == null || resolve.length() == 0) {        // 从系统属性中获取解析文件路径        resolveFile = System.getProperty("dubbo.resolve.file");        // 从指定位置加载配置文件        if (resolveFile == null || resolveFile.length() == 0) {            File userResolveFile =                 new File(new File(System.getProperty("user.home")), "dubbo-resolve.properties");            if (userResolveFile.exists()) {                // 获取文件绝对路径                resolveFile = userResolveFile.getAbsolutePath();            }        }
        if (resolveFile != null && resolveFile.length() > 0) {            Properties properties = new Properties();            FileInputStream fis = null;            try {                fis = new FileInputStream(new File(resolveFile));                // 从文件中加载配置                properties.load(fis);            }             // 获取与接口名对应的配置            resolve = properties.getProperty(interfaceName);        }    }    if (resolve != null && resolve.length() > 0) {        // 将resolve赋值给url,用于点对点直连        url = resolve;    }
    if (consumer != null) {        if (application == null) {            application = consumer.getApplication();        }        if (module == null) {            module = consumer.getModule();        }        if (registries == null) {            registries = consumer.getRegistries();        }        if (monitor == null) {            monitor = consumer.getMonitor();        }    }    if (module != null) {        if (registries == null) {            registries = module.getRegistries();        }        if (monitor == null) {            monitor = module.getMonitor();        }    }
    if (application != null) {        if (registries == null) {            registries = application.getRegistries();        }        if (monitor == null) {            monitor = application.getMonitor();        }    }        // 检测Application合法性    checkApplication();    // 检测本地存根配置合法性    checkStubAndMock(interfaceClass);    // 添加side、协议版本信息、时间戳和进程号等信息到map中,side表示处于哪一侧,目前是处于服务消费者侧    Map<String, String> map = new HashMap<String, String>();    Map<Object, Object> attributes = new HashMap<Object, Object>();    map.put(Constants.SIDE_KEY, Constants.CONSUMER_SIDE);    map.put(Constants.DUBBO_VERSION_KEY, Version.getProtocolVersion());    map.put(Constants.TIMESTAMP_KEY, String.valueOf(System.currentTimeMillis()));    if (ConfigUtils.getPid() > 0) {        map.put(Constants.PID_KEY, String.valueOf(ConfigUtils.getPid()));    }
    // 非泛化服务    if (!isGeneric()) {        // 获取版本        String revision = Version.getVersion(interfaceClass, version);        if (revision != null && revision.length() > 0) {            map.put("revision", revision);        }        // 获取接口方法列表,并添加到map中        String[] methods = Wrapper.getWrapper(interfaceClass).getMethodNames();        if (methods.length == 0) {            map.put("methods", Constants.ANY_VALUE);        } else {            map.put("methods", StringUtils.join(new HashSet<String>(Arrays.asList(methods)), ","));        }    }    map.put(Constants.INTERFACE_KEY, interfaceName);    // 将ApplicationConfig、ConsumerConfig、ReferenceConfig等对象的字段信息添加到map中    appendParameters(map, application);    appendParameters(map, module);    appendParameters(map, consumer, Constants.DEFAULT_KEY);    appendParameters(map, this);
    // 形如com.alibaba.dubbo.demo.DemoService    String prefix = StringUtils.getServiceKey(map);    if (methods != null && !methods.isEmpty()) {        // 遍历MethodConfig列表        for (MethodConfig method : methods) {            appendParameters(map, method, method.getName());            String retryKey = method.getName() + ".retry";            // 检测map是否包含methodName.retry            if (map.containsKey(retryKey)) {                String retryValue = map.remove(retryKey);                if ("false".equals(retryValue)) {                    // 添加重试次数配置methodName.retries                    map.put(method.getName() + ".retries", "0");                }            }            // 添加MethodConfig中的“属性”字段到attributes            // 比如onreturn、onthrow、oninvoke等            appendAttributes(attributes, method, prefix + "." + method.getName());            checkAndConvertImplicitConfig(method, map, attributes);        }    }
    // 获取服务消费者ip地址    String hostToRegistry = ConfigUtils.getSystemProperty(Constants.DUBBO_IP_TO_REGISTRY);    if (hostToRegistry == null || hostToRegistry.length() == 0) {        hostToRegistry = NetUtils.getLocalHost();    } else if (isInvalidLocalHost(hostToRegistry)) {        throw new IllegalArgumentException("");    }    map.put(Constants.REGISTER_IP_KEY, hostToRegistry);    // 存储attributes到系统上下文中    StaticContext.getSystemContext().putAll(attributes);    // 创建代理类,核心    ref = createProxy(map);    // 根据服务名,ReferenceConfig,代理类构建ConsumerModel,    // 并将ConsumerModel存入到ApplicationModel中    ConsumerModel consumerModel =                 new ConsumerModel(getUniqueServiceName(), this, ref, interfaceClass.getMethods());    ApplicationModel.initConsumerModel(getUniqueServiceName(), consumerModel);}

3.2、创建Invoker及代理

上述init()方法的核心代码是ref = createProxy(map),下面分析这个方法。

3.2.1、总体分析

// 从字面意思上来看,createProxy似乎只是用于创建代理对象的,但实际上并非如此,// 该方法还会调用其他方法构建以及合并Invoker实例private T createProxy(Map<String, String> map) {    URL tmpUrl = new URL("temp", "localhost", 0, map);    final boolean isJvmRefer;    if (isInjvm() == null) {        // url配置被指定,则不做本地引用,我理解该url是用来做直连的        if (url != null && url.length() > 0) {            isJvmRefer = false;        }        // 根据url的协议、scope以及injvm等参数检测是否需要本地引用        // 比如如果用户显式配置了scope=local,此时isInjvmRefer返回true        else if (InjvmProtocol.getInjvmProtocol().isInjvmRefer(tmpUrl)) {            isJvmRefer = true;        } else {            isJvmRefer = false;        }    } else {        // 获取injvm配置值        isJvmRefer = isInjvm().booleanValue();    }
    // 本地引用    if (isJvmRefer) {        // 生成本地引用URL,协议为injvm        URL url = new URL(Constants.LOCAL_PROTOCOL, NetUtils.LOCALHOST, 0,                                                    interfaceClass.getName()).addParameters(map);        // 调用refer方法构建InjvmInvoker实例        invoker = refprotocol.refer(interfaceClass, url);    }
    // 远程引用    else {        // url不为空,表明用户可能想进行点对点调用        if (url != null && url.length() > 0) {            String[] us = Constants.SEMICOLON_SPLIT_PATTERN.split(url);            if (us != null && us.length > 0) {                for (String u : us) {                    URL url = URL.valueOf(u);                    if (url.getPath() == null || url.getPath().length() == 0) {                        url = url.setPath(interfaceName);                    }                    if (Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())) {                        urls.add(url.addParameterAndEncoded(Constants.REFER_KEY,                                                               StringUtils.toQueryString(map)));                    } else {                        urls.add(ClusterUtils.mergeUrl(url, map));                    }                }            }        }
        else {            // 加载注册中心url            List<URL> us = loadRegistries(false);            if (us != null && !us.isEmpty()) {                for (URL u : us) {                    URL monitorUrl = loadMonitor(u);                    if (monitorUrl != null) {                        map.put(Constants.MONITOR_KEY, URL.encode(monitorUrl.toFullString()));                    }                    // 添加refer参数到url中,并将url添加到urls中                    urls.add(u.addParameterAndEncoded(Constants.REFER_KEY,                                                              StringUtils.toQueryString(map)));                }            }            // 未配置注册中心,抛出异常            if (urls.isEmpty()) {                // 抛异常            }        }
        // 单个注册中心或服务提供者(服务直连,下同)        if (urls.size() == 1) {            // 1. 调用RegistryProtocol的refer构建Invoker实例,普通情况下走这个逻辑            invoker = refprotocol.refer(interfaceClass, urls.get(0));        }
        // 多个注册中心或多个服务提供者,或者两者混合        else {            List<Invoker<?>> invokers = new ArrayList<Invoker<?>>();            URL registryURL = null;             for (URL url : urls) {                // 获取所有的Invoker,通过refprotocol调用refer构建Invoker,refprotocol会在运行时                // 根据url协议头加载指定的Protocol实例,并调用实例的refer方法                invokers.add(refprotocol.refer(interfaceClass, url));                if (Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())) {                    registryURL = url;                }            }            // 如果注册中心链接不为空,则将使用AvailableCluster            if (registryURL != null) {                URL u = registryURL.addParameter(Constants.CLUSTER_KEY, AvailableCluster.NAME);                // 创建StaticDirectory实例,并由Cluster对多个Invoker进行合并                invoker = cluster.join(new StaticDirectory(u, invokers));            } else {                invoker = cluster.join(new StaticDirectory(invokers));            }        }    }
    Boolean c = check;    if (c == null && consumer != null) {        c = consumer.isCheck();    }    if (c == null) {        // default true        c = true;    }    // invoker可用性检查    if (c && !invoker.isAvailable()) {        // 抛异常    }    // 2. 生成代理类,核心    // Invoker创建完毕后,接下来要做的事情是为服务接口生成代理对象.有了代理对象,    // 即可进行远程调用.代理对象生成的入口方法为ProxyFactory的getProxy    return (T) proxyFactory.getProxy(invoker);}

3.2.2、创建Invoker

// 下面分析创建Invoker,单个注册中心或服务提供者(服务直连,下同)if (urls.size() == 1) {    // 1. 调用RegistryProtocol的refer构建Invoker实例,普通情况下走这个逻辑    invoker = refprotocol.refer(interfaceClass, urls.get(0));}
  public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException {    // protocol为zookeeper,调试加的    String protocol = url.getParameter(Constants.REGISTRY_KEY, Constants.DEFAULT_REGISTRY);    url = url.setProtocol(url.getParameter(Constants.REGISTRY_KEY,                                Constants.DEFAULT_REGISTRY)).removeParameter(Constants.REGISTRY_KEY);    // 获取注册中心实例    Registry registry = registryFactory.getRegistry(url);    // 这里的type是""    if (RegistryService.class.equals(type)) {        return proxyFactory.getInvoker((T) registry, type, url);    }
    // 将url查询字符串转为Map    Map<String, String> qs =                       StringUtils.parseQueryString(url.getParameterAndDecoded(Constants.REFER_KEY));    // 获取group配置    String group = qs.get(Constants.GROUP_KEY);    if (group != null && group.length() > 0) {        if ((Constants.COMMA_SPLIT_PATTERN.split(group)).length > 1                || "*".equals(group)) {            // 通过SPI加载MergeableCluster实例,并调用doRefer继续执行服务引用逻辑            return doRefer(getMergeableCluster(), registry, type, url);        }    }    // 调用doRefer继续执行服务引用逻辑    return doRefer(cluster, registry, type, url);}

3.2.3、创建代理