Dubbo源码学习笔记(提供方服务暴露serviceBean)

 前面一篇文章主要是对dubbo的xml中所配置的内容进行解析以及参数的绑定,从而实现整个bean的注册,文章的结尾也有提到,dubbo的服务暴露以及服务订阅是通过子类进行扩展并协同父类实现相应的功能,下面主要来解读一下serviceBean服务的暴露,直接源码如下:


/*最主要的两个bean,一个服务提供方的暴露服务ServiceBean以及一个服务消费方的订阅服务ReferenceBean。
首先来看serviceBean的源码:*/
	
	
	public class ServiceBean<T> extends ServiceConfig<T> implements InitializingBean, DisposableBean, ApplicationContextAware, ApplicationListener, BeanNameAware {

    private static final long serialVersionUID = 213195494150089726L;

    private static transient ApplicationContext SPRING_CONTEXT;

    private final transient Service service;

    private transient ApplicationContext applicationContext;

    private transient String beanName;

    private transient boolean supportedApplicationListener;

    public ServiceBean() {
        super(); /*ServiceConfig必须先进行,这里与另外的几个Config是没有什么区别的。*/
        this.service = null;
    }

    public ServiceBean(Service service) {
        super(service);
        this.service = service;
    }

    public static ApplicationContext getSpringContext() {
        return SPRING_CONTEXT;
    }

	/*实现了ApplicationContextAware,重写了setApplicationContext,以便将spring中的applicationContext拿到dubbo中来使用,并保存到SpringExtensionFactory*/
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
        SpringExtensionFactory.addApplicationContext(applicationContext);
        if (applicationContext != null) {
            SPRING_CONTEXT = applicationContext;
            try {
                Method method = applicationContext.getClass().getMethod("addApplicationListener", new Class<?>[]{ApplicationListener.class}); 
                method.invoke(applicationContext, new Object[]{this});
                supportedApplicationListener = true;
            } catch (Throwable t) {
                if (applicationContext instanceof AbstractApplicationContext) {
                    try {
                        Method method = AbstractApplicationContext.class.getDeclaredMethod("addListener", new Class<?>[]{ApplicationListener.class}); 
                        if (!method.isAccessible()) {
                            method.setAccessible(true);
                        }
                        method.invoke(applicationContext, new Object[]{this});
                        supportedApplicationListener = true;
                    } catch (Throwable t2) {
                    }
                }
            }
        }
    }
	/*实现了BeanNameAware接口,重写了此方法*/
    public void setBeanName(String name) {
        this.beanName = name;
    }

    /**
     * Gets associated {@link Service}
     *
     * @return associated {@link Service}
     */
    public Service getService() {
        return service;
    }
	/*服务监听,没有设置延迟或者延迟为-1,dubbo会在Spring实例化完bean之后,在刷新容器最后一步发布ContextRefreshEvent事件的时候,
	通知实现了ApplicationListener的类进行回调onApplicationEvent,dubbo会在这个方法中发布服务。*/
    public void onApplicationEvent(ApplicationEvent event) {
        if (ContextRefreshedEvent.class.getName().equals(event.getClass().getName())) {
            if (isDelay() && !isExported() && !isUnexported()) {
                if (logger.isInfoEnabled()) {
                    logger.info("The service ready on spring started. service: " + getInterface());
                }
                export();
            }
        }
    }

    private boolean isDelay() {
        Integer delay = getDelay();
        ProviderConfig provider = getProvider();
        if (delay == null && provider != null) {
            delay = provider.getDelay();
        }
        return supportedApplicationListener && (delay == null || delay == -1);
    }

    @SuppressWarnings({"unchecked", "deprecation"})
	/*dubbo在Spring实例化bean(initializeBean)的时候会对实现了InitializingBean的类进行回调,回调方法就是此方法*/
    public void afterPropertiesSet() throws Exception {
		/*此serviceBean提供者为空*/
        if (getProvider() == null) {
			/*applicationContext不为空的情况下则从applicationContext中获取提供者bean集合,比如:在提供方配置的<dubbo:provider>*/
            Map<String, ProviderConfig> providerConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ProviderConfig.class, false, false);
            if (providerConfigMap != null && providerConfigMap.size() > 0) {
				/*applicationContext不为空的情况下则从applicationContext中获取协议bean集合,比如:在提供方配置的<dubbo:protocol>*/
                Map<String, ProtocolConfig> protocolConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ProtocolConfig.class, false, false);
                /*没有获取到协议配置 && 提供者集合中有元素*/
				if ((protocolConfigMap == null || protocolConfigMap.size() == 0)
                        && providerConfigMap.size() > 1) {    /*兼容旧版本*/
                    List<ProviderConfig> providerConfigs = new ArrayList<ProviderConfig>();
					/*遍历提供者bean集合*/
                    for (ProviderConfig config : providerConfigMap.values()) {
                        if (config.isDefault() != null && config.isDefault().booleanValue()) {
                            providerConfigs.add(config);
                        }
                    }
					/*为此serviceBean添加提供者列表,设置到对应的属性*/
                    if (providerConfigs.size() > 0) {
                        setProviders(providerConfigs);
                    }
				/*反之,直接遍历提供者集合*/
                } else {
                    ProviderConfig providerConfig = null;
					/*遍历提供者bean集合*/
                    for (ProviderConfig config : providerConfigMap.values()) {
                        if (config.isDefault() == null || config.isDefault().booleanValue()) {
							/*如果在这个providerConfigMap遍历出一样配置,将抛出异常,提示重复的提供者配置*/
                            if (providerConfig != null) {
                                throw new IllegalStateException("Duplicate provider configs: " + providerConfig + " and " + config);
                            }
                            providerConfig = config;
                        }
                    }
					/*为此serviceBean设置提供者,设置到对应的属性*/
                    if (providerConfig != null) {
                        setProvider(providerConfig);
                    }
                }
            }
        }
		/*此serviceBean应用配置信息为空 && (提供者为空 || 提供者中也没有配置应用信息)*/
        if (getApplication() == null
                && (getProvider() == null || getProvider().getApplication() == null)) {
				/*applicationContext不为空的情况下则从applicationContext中获取应用配置bean集合,比如:在提供方配置的<dubbo:application name="">则
				 * 这里拿到的就是这样{dubbo_zht_core=<dubbo:application name="dubbo_zht_core" id="dubbo_zht_core" />}*/
				 */
            Map<String, ApplicationConfig> applicationConfigMap = applicationContext == null ? 
            		null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ApplicationConfig.class, false, false);
            if (applicationConfigMap != null && applicationConfigMap.size() > 0) {
                ApplicationConfig applicationConfig = null;
				/*遍历应用配置信息bean集合*/
                for (ApplicationConfig config : applicationConfigMap.values()) {
                    if (config.isDefault() == null || config.isDefault().booleanValue()) {
						/*应用配置信息不能够重复*/
                        if (applicationConfig != null) {
                            throw new IllegalStateException("Duplicate application configs: " + applicationConfig + " and " + config);
                        }
                        applicationConfig = config;
                    }
                }
				/*为此serviceBean设置应用信息,设置到对应的属性*/
                if (applicationConfig != null) {
                    setApplication(applicationConfig);
                }
            }
        }
		/*此serviceBean模块配置信息为空 && (提供者为空 || 提供者中也没有配置模块信息)*/
        if (getModule() == null
                && (getProvider() == null || getProvider().getModule() == null)) {
				/*applicationContext不为空的情况下则从applicationContext中获取模块配置信息bean集合,比如:在提供方配置的 <dubbo:module> */
            Map<String, ModuleConfig> moduleConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ModuleConfig.class, false, false);
            if (moduleConfigMap != null && moduleConfigMap.size() > 0) {
                ModuleConfig moduleConfig = null;
                /*遍历模块配置信息bean集合*/
				for (ModuleConfig config : moduleConfigMap.values()) {
                    if (config.isDefault() == null || config.isDefault().booleanValue()) {
						/*模块配置信息不能重复*/
                        if (moduleConfig != null) {
                            throw new IllegalStateException("Duplicate module configs: " + moduleConfig + " and " + config);
                        }
                        moduleConfig = config;
                    }
                }
				/*为此serviceBean设置模块配置信息,设置到对应的属性*/
                if (moduleConfig != null) {
                    setModule(moduleConfig);
                }
            }
        }
		/*此serviceBean注册中心配置信息为空 && (提供者为空 || 提供者中也没有配置注册中心信息) && (应用配置信息为空 || 应用配置信息中也没有配置注册中心)*/
        if ((getRegistries() == null || getRegistries().size() == 0)
                && (getProvider() == null || getProvider().getRegistries() == null || getProvider().getRegistries().size() == 0)
                && (getApplication() == null || getApplication().getRegistries() == null || getApplication().getRegistries().size() == 0)) {
				/*applicationContext不为空的情况下则从applicationContext中获取注册中心配置信息bean集合,比如:在提供方配置的 <dubbo:registry>*/
            Map<String, RegistryConfig> registryConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, RegistryConfig.class, false, false);
			if (registryConfigMap != null && registryConfigMap.size() > 0) {
                List<RegistryConfig> registryConfigs = new ArrayList<RegistryConfig>();
				/*遍历注册中心配置bean集合*/
                for (RegistryConfig config : registryConfigMap.values()) {
                    if (config.isDefault() == null || config.isDefault().booleanValue()) {
                        registryConfigs.add(config);
                    }
                }
				/*为此serviceBean的父类设置注册中心配置信息,设置到对应的属性*/
                if (registryConfigs != null && registryConfigs.size() > 0) {
                    super.setRegistries(registryConfigs);
                }
            }
        }
		/*此serviceBean监控中心为空 && (提供者为空 || 提供者中也没有监控中心信息) && (应用配置信息为空 || 应用配置信息中也没有配置监控中心))*/
        if (getMonitor() == null
                && (getProvider() == null || getProvider().getMonitor() == null)
                && (getApplication() == null || getApplication().getMonitor() == null)) {
				/*applicationContext不为空的情况下则从applicationContext中获取监控中心配置信息bean集合,比如:在提供方配置的 <dubbo:monitor>*/
            Map<String, MonitorConfig> monitorConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, MonitorConfig.class, false, false);
            if (monitorConfigMap != null && monitorConfigMap.size() > 0) {
                MonitorConfig monitorConfig = null;
                for (MonitorConfig config : monitorConfigMap.values()) {
                    if (config.isDefault() == null || config.isDefault().booleanValue()) {
						/*监控中心的配置信息不能够重复*/
                        if (monitorConfig != null) {
                            throw new IllegalStateException("Duplicate monitor configs: " + monitorConfig + " and " + config);
                        }
                        monitorConfig = config;
                    }
                }
				/*为此serviceBean设置监控中心配置信息,设置到对应的属性*/
                if (monitorConfig != null) {
                    setMonitor(monitorConfig);
                }
            }
        }
		/*此serviceBean协议配置为空 && (提供者为空 || 提供者中也没有配置协议信息)*/
        if ((getProtocols() == null || getProtocols().size() == 0)
                && (getProvider() == null || getProvider().getProtocols() == null || getProvider().getProtocols().size() == 0)) {
				/*applicationContext不为空的情况下则从applicationContext中获取协议配置信息bean集合,比如:在提供方配置的 <dubbo:protocol>*/
            Map<String, ProtocolConfig> protocolConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ProtocolConfig.class, false, false);
            if (protocolConfigMap != null && protocolConfigMap.size() > 0) {
                List<ProtocolConfig> protocolConfigs = new ArrayList<ProtocolConfig>();
				/*遍历协议信息bean集合,取出协议装入列表中*/
                for (ProtocolConfig config : protocolConfigMap.values()) {
                    if (config.isDefault() == null || config.isDefault().booleanValue()) {
                        protocolConfigs.add(config);
                    }
                }
				/*为此serviceBean设置协议配置信息列表,设置到对应的属性*/
                if (protocolConfigs != null && protocolConfigs.size() > 0) {
                    super.setProtocols(protocolConfigs);
                }
            }
        }
		/*此serviceBean服务路径配置为空 */
        if (getPath() == null || getPath().length() == 0) {
			/*bean的名称不为空 && 服务接口名不为空 && bean的名称是与服务接口名称开头,这个beanName就是xml中<dubbo:service interface=""/>*/
            if (beanName != null && beanName.length() > 0
                    && getInterface() != null && getInterface().length() > 0
                    && beanName.startsWith(getInterface())) {
				/*会使用正则表达式对beanName进行校验是否合法*/
                setPath(beanName);
            }
        }
		/*如果设置了延迟暴露,dubbo在这个export方法里面会另外创建一个线程进行服务的发布*/
        if (!isDelay()) {
            export();/*这里就是真正服务进行暴露的入口,调用父类的方法*/
        }
    }
	/*实现了DisposableBean,在bean销毁前做哪些操作?则调用unexport*/
    public void destroy() throws Exception {
        unexport();
    }

}

/*下面为调用父类ServiceConfig中export方法以及关联方法源码:*/
  public synchronized void export() {
        if (provider != null) {
            if (export == null) {
                export = provider.getExport();
            }
            if (delay == null) {
                delay = provider.getDelay();
            }
        }
        if (export != null && !export) {
            return;
        }
			/*如果设置了延迟暴露,那么这里会创建一个线程进行延迟处理*/
        if (delay != null && delay > 0) {
            delayExportExecutor.schedule(new Runnable() {
                public void run() {
                    doExport();
                }
            }, delay, TimeUnit.MILLISECONDS);
        } else {
            doExport();
        }
    }

    protected synchronized void doExport() {
        if (unexported) {
            throw new IllegalStateException("Already unexported!");
        }
        if (exported) {
            return;
        }
        exported = true;
		/*暴露接口名称不能为空*/
        if (interfaceName == null || interfaceName.length() == 0) {
            throw new IllegalStateException("<dubbo:service interface=\"\" /> interface not allow null!");
        }
		/*校验服务提供方是否配有默认的提供者,即使在服务提供方配了一个无法找到的IP以及端口的provider在这里也不会报错*/
        checkDefault();
        if (provider != null) {
            if (application == null) {
                application = provider.getApplication();
            }
            if (module == null) {
                module = provider.getModule();
            }
            if (registries == null) {
                registries = provider.getRegistries();
            }
            if (monitor == null) {
                monitor = provider.getMonitor();
            }
            if (protocols == null) {
                protocols = provider.getProtocols();
            }
        }
        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();
            }
        }
        if (ref instanceof GenericService) {
            interfaceClass = GenericService.class;
            if (StringUtils.isEmpty(generic)) {
                generic = Boolean.TRUE.toString();
            }
        } else {
            try {
                interfaceClass = Class.forName(interfaceName, true, Thread.currentThread()
                        .getContextClassLoader());
            } catch (ClassNotFoundException e) {
                throw new IllegalStateException(e.getMessage(), e);
            }
			/*如果配置了<dubbo:method>则会校验此interfaceClass中的方法与你配置的是否一致,如果你配的这个方法在此interfaceClass中根本找不到则会抛出IllegalStateException异常,*/
			/*当然,如果你配了个<dubbo:method>空标签那么早就在DubboBeanDefinitionParser中抛出异常了,还走不到这里*/
            checkInterfaceAndMethods(interfaceClass, methods);
			/*校验<dubbo:service>中interface的实例是不是ref指向的这个实例,如果ref为空或者这两个不匹配,也就是没有实现接口则会抛出IllegalStateException异常*/
            checkRef();
            generic = Boolean.FALSE.toString();
        }
		/*如果是本地服务,则再服务名称后面加上Local*/
        if (local != null) {
            if ("true".equals(local)) {
                local = interfaceName + "Local";
            }
            Class<?> localClass;
            try {
                localClass = ClassHelper.forNameWithThreadContextClassLoader(local);
            } catch (ClassNotFoundException e) {
                throw new IllegalStateException(e.getMessage(), e);
            }
            if (!interfaceClass.isAssignableFrom(localClass)) {
                throw new IllegalStateException("The local implementation class " + localClass.getName() + " not implement interface " + interfaceName);
            }
        }
		/*如果是远程服务,则再服务名称后面加上Stub*/
        if (stub != null) {
            if ("true".equals(stub)) {
                stub = interfaceName + "Stub";
            }
            Class<?> stubClass;
            try {
                stubClass = ClassHelper.forNameWithThreadContextClassLoader(stub);
            } catch (ClassNotFoundException e) {
                throw new IllegalStateException(e.getMessage(), e);
            }
            if (!interfaceClass.isAssignableFrom(stubClass)) {
                throw new IllegalStateException("The stub implementation class " + stubClass.getName() + " not implement interface " + interfaceName);
            }
        }
		/*校验服务方应用配置信息是否为空,如果为空则根据key到系统属性中获取,如果还是没有获取到则会抛出异常,如果获取到了则会新创建一个ApplicationConfig,并将系统中获取的对应的属性值赋值给ApplicationConfig。*/
        checkApplication();
		/*校验注册中心配置信息是否为空,如果为空则根据key到系统属性中获取,如果还是没有获取到则会抛出异常,如果获取到了则会新创建一个RegistryConfig,并将系统中获取的对应的属性值赋值给RegistryConfig,有多个则循环多次操作。*/
        checkRegistry();
		/*校验协议配置信息是否为空,如果为空则试图从<dubbo:provider>中获取,如果provider也是null,则默认使用dubbo协议*/
        checkProtocol();
		/*将当前对象实例传入此方法进行属性完整化,如serviceBean*/
        appendProperties(this);
		/*检查远端和本地服务接口真实存在(是否可load)以及是否可以服务降级*/
        checkStubAndMock(interfaceClass);
        if (path == null || path.length() == 0) {
            path = interfaceName;
        }
		 /*暴露地址*/
        doExportUrls();
    }


    public synchronized void unexport() {
        if (!exported) {
            return;
        }
        if (unexported) {
            return;
        }
        if (exporters != null && exporters.size() > 0) {
            for (Exporter<?> exporter : exporters) {
                try {
                    exporter.unexport();
                } catch (Throwable t) {
                    logger.warn("unexpected err when unexport" + exporter, t);
                }
            }
            exporters.clear();
        }
        unexported = true;
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    private void doExportUrls() {
		/*将所有需要的信息进行组装,成为注册中心的URL(ip、注册接口、pid、时间戳)*/
        List<URL> registryURLs = loadRegistries(true);
        for (ProtocolConfig protocolConfig : protocols) {
            doExportUrlsFor1Protocol(protocolConfig, registryURLs);
        }
    }

    private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List<URL> registryURLs) {
        String name = protocolConfig.getName();
		/*如果协议名称为空怎么默认使用dubbo*/
        if (name == null || name.length() == 0) {
            name = "dubbo";
        }

        Map<String, String> map = new HashMap<String, String>();
        map.put(Constants.SIDE_KEY, Constants.PROVIDER_SIDE);
        map.put(Constants.DUBBO_VERSION_KEY, Version.getVersion());
        map.put(Constants.TIMESTAMP_KEY, String.valueOf(System.currentTimeMillis()));
        if (ConfigUtils.getPid() > 0) {
            map.put(Constants.PID_KEY, String.valueOf(ConfigUtils.getPid()));
        }
		/*将必要的信息都添加进map中*/
        appendParameters(map, application);
        appendParameters(map, module);
        appendParameters(map, provider, Constants.DEFAULT_KEY);
        appendParameters(map, protocolConfig);
        appendParameters(map, this);
        if (methods != null && methods.size() > 0) {
            for (MethodConfig method : methods) {
                appendParameters(map, method, method.getName());
                String retryKey = method.getName() + ".retry";
                if (map.containsKey(retryKey)) {
                    String retryValue = map.remove(retryKey);
                    if ("false".equals(retryValue)) {
                        map.put(method.getName() + ".retries", "0");
                    }
                }
                List<ArgumentConfig> arguments = method.getArguments();
                if (arguments != null && arguments.size() > 0) {
                    for (ArgumentConfig argument : arguments) {
                        /*类型自动转换.  */
                        if (argument.getType() != null && argument.getType().length() > 0) {
                            Method[] methods = interfaceClass.getMethods();
                            /*遍历所有方法 */
                            if (methods != null && methods.length > 0) {
                                for (int i = 0; i < methods.length; i++) {
                                    String methodName = methods[i].getName();
                                    /*匹配方法名称,获取方法签名.  */
                                    if (methodName.equals(method.getName())) {
                                        Class<?>[] argtypes = methods[i].getParameterTypes();
                                        /*一个方法中单个callback  */
                                        if (argument.getIndex() != -1) {
                                            if (argtypes[argument.getIndex()].getName().equals(argument.getType())) {
                                                appendParameters(map, argument, method.getName() + "." + argument.getIndex());
                                            } else {
                                                throw new IllegalArgumentException("argument config error : the 
index attribute and type attirbute not match :index :" + argument.getIndex() + ", type:" + argument.getType());
                                            }
                                        } else {
                                            /*一个方法中多个callback  */
                                            for (int j = 0; j < argtypes.length; j++) {
                                                Class<?> argclazz = argtypes[j];
                                                if (argclazz.getName().equals(argument.getType())) {
                                                    appendParameters(map, argument, method.getName() + "." + j);
                                                    if (argument.getIndex() != -1 && argument.getIndex() != j) {
                                                        throw new IllegalArgumentException("argument config error : 
the index attribute and type attirbute not match :index :" + argument.getIndex() + ", type:" + argument.getType());
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        } else if (argument.getIndex() != -1) {
                            appendParameters(map, argument, method.getName() + "." + argument.getIndex());
                        } else {
                            throw new IllegalArgumentException("argument config must set index or type 
attribute.eg: <dubbo:argument index='0' .../> or <dubbo:argument type=xxx .../>");
                        }

                    }
                }
            } /* end of methods for*/
        }

        if (ProtocolUtils.isGeneric(generic)) {
            map.put("generic", generic);
            map.put("methods", Constants.ANY_VALUE);
        } else {
            String revision = Version.getVersion(interfaceClass, version);
            if (revision != null && revision.length() > 0) {
                map.put("revision", revision);
            }
			/*拿到暴露服务接口实例的所有方法,如果没有则使用*代替所有,否则就使用逗号连接起来*/
            String[] methods = Wrapper.getWrapper(interfaceClass).getMethodNames();
            if (methods.length == 0) {
                logger.warn("NO method found in service interface " + interfaceClass.getName());
                map.put("methods", Constants.ANY_VALUE);
            } else {
                map.put("methods", StringUtils.join(new HashSet<String>(Arrays.asList(methods)), ","));
            }
        }
        if (!ConfigUtils.isEmpty(token)) {
            if (ConfigUtils.isDefault(token)) {
                map.put("token", UUID.randomUUID().toString());
            } else {
                map.put("token", token);
            }
        }
        if ("injvm".equals(protocolConfig.getName())) {
            protocolConfig.setRegister(false);
            map.put("notify", "false");
        }
        /*  导出服务 */
        String contextPath = protocolConfig.getContextpath();
        if ((contextPath == null || contextPath.length() == 0) && provider != null) {
            contextPath = provider.getContextpath();
        }
		/*provider注册&监听ip地址,注册与监听ip可独立配置 配置优先级:系统环境变量 -> java命令参数-D -> 
		 * 配置文件host属性 -> /etc/hosts中hostname-ip映射关系 -> 默认联通注册中心地址的网卡地址 -> 第一个可用的网卡地址*/
        String host = this.findConfigedHosts(protocolConfig, registryURLs, map);
        /*provider注册&监听端口,注册与监听port可独立配置 配置优先级:启动环境变量 -> java命令参数-D -> protocol配置文件port属性配置 -> 协议默认端口*/
		Integer port = this.findConfigedPorts(protocolConfig, name, map);
		/*创建服务所在url  */
        URL url = new URL(name, host, port, (contextPath == null || contextPath.length() == 0 ? "" : contextPath + "/") + path, map);

        if (ExtensionLoader.getExtensionLoader(ConfiguratorFactory.class)
                .hasExtension(url.getProtocol())) {
            url = ExtensionLoader.getExtensionLoader(ConfiguratorFactory.class)
                    .getExtension(url.getProtocol()).getConfigurator(url).configure(url);
        }
		/*获取服务暴露作用域*/
        String scope = url.getParameter(Constants.SCOPE_KEY);
           /*配置为none不暴露,如果什么都没配的话即暴露本地又暴露远程*/
        if (!Constants.SCOPE_NONE.toString().equalsIgnoreCase(scope)) {

            /*配置不是remote的情况下做本地暴露 (配置为remote,则表示只暴露远程服务)*/
            if (!Constants.SCOPE_REMOTE.toString().equalsIgnoreCase(scope)) {
                exportLocal(url);
            }
            /*如果配置不是local则暴露为远程服务.(配置为local,则表示只暴露本地服务)*/
            if (!Constants.SCOPE_LOCAL.toString().equalsIgnoreCase(scope)) {
                if (logger.isInfoEnabled()) {
                    logger.info("Export dubbo service " + interfaceClass.getName() + " to url " + url);
                }
                if (registryURLs != null && registryURLs.size() > 0
                        && url.getParameter("register", true)) {
                    for (URL registryURL : registryURLs) {
                        url = url.addParameterIfAbsent("dynamic", registryURL.getParameter("dynamic"));
                        URL monitorUrl = loadMonitor(registryURL);
                        if (monitorUrl != null) {
                            url = url.addParameterAndEncoded(Constants.MONITOR_KEY, monitorUrl.toFullString());
                        }
                        if (logger.isInfoEnabled()) {
                            logger.info("Register dubbo service " + interfaceClass.getName() + " url " + url + " to registry " + registryURL);
                        }
						/*通过proxyFactory获取一个AbstractProxyInvoker实例Invoker,这个proxyFactory是JavassistProxyFactory、JdkProxyFactory中的一个,我在调试时看到的是JavassistProxyFactory*/
                        Invoker<?> invoker = proxyFactory.getInvoker(ref, (Class) interfaceClass, registryURL.addParameterAndEncoded(Constants.EXPORT_KEY, url.toFullString()));
						/*protocol根据实际调用时的不同而使用的协议则不同,我在调试时看到的是RegistryProtocol,在调RegistryProtocol的export前会先调用ProtocollistenerWrapper的export方法对protocol实例wrapper*/
                        Exporter<?> exporter = protocol.export(invoker);
                        exporters.add(exporter);
                    }
                } else {
                    Invoker<?> invoker = proxyFactory.getInvoker(ref, (Class) interfaceClass, url);

                    Exporter<?> exporter = protocol.export(invoker);
                    exporters.add(exporter);
                }
            }
        }
        this.urls.add(url);
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    private void exportLocal(URL url) {
        if (!Constants.LOCAL_PROTOCOL.equalsIgnoreCase(url.getProtocol())) {
            URL local = URL.valueOf(url.toFullString())
                    .setProtocol(Constants.LOCAL_PROTOCOL)
                    .setHost(LOCALHOST)
                    .setPort(0);
            Exporter<?> exporter = protocol.export(
                    proxyFactory.getInvoker(ref, (Class) interfaceClass, local));
            exporters.add(exporter);
            logger.info("Export dubbo service " + interfaceClass.getName() + " to local registry");
        }
    }


     /**
     * provider注册&监听ip地址,注册与监听ip可独立配置
     * 配置优先级:系统环境变量 -> java命令参数-D -> 配置文件host属性 -> /etc/hosts中hostname-ip映射关系 -> 默认联通注册中心地址的网卡地址 -> 第一个可用的网卡地址
     *
     * @param protocolConfig
     * @param registryURLs
     * @param map
     * @return
     */
    private String findConfigedHosts(ProtocolConfig protocolConfig, List<URL> registryURLs, Map<String, String> map) {
        boolean anyhost = false;
		/*从系统环境变量中获取IP*/
        String hostToBind = getValueFromConfig(protocolConfig, Constants.DUBBO_IP_TO_BIND);
        if (hostToBind != null && hostToBind.length() > 0 && isInvalidLocalHost(hostToBind)) {
            throw new IllegalArgumentException("Specified invalid bind ip from property:" + Constants.DUBBO_IP_TO_BIND + ", value:" + hostToBind);
        }

        /* 如果没通过系统环境变量设置bind ip,则继续按优先级查找*/
        if (hostToBind == null || hostToBind.length() == 0) {
			/*从配置文件中获取host*/
            hostToBind = protocolConfig.getHost();
            if (provider != null && (hostToBind == null || hostToBind.length() == 0)) {
                hostToBind = provider.getHost();
            }
			/*是否为有效的IP,也就是说在配置文件中<dubbo:protocol>配置的host不是有效的话则接着按照优先级往下找*/
            if (isInvalidLocalHost(hostToBind)) {
                anyhost = true;
                try {
					/*etc/hosts中hostname-ip映射关系*/
                    hostToBind = InetAddress.getLocalHost().getHostAddress();
                } catch (UnknownHostException e) {
                    logger.warn(e.getMessage(), e);
                }
                if (isInvalidLocalHost(hostToBind)) {
                    if (registryURLs != null && registryURLs.size() > 0) {
                        for (URL registryURL : registryURLs) {
                            try {
                                Socket socket = new Socket();
                                try {
									/*联通注册中心地址的网卡地址*/
                                    SocketAddress addr = new InetSocketAddress(registryURL.getHost(), registryURL.getPort());
                                    socket.connect(addr, 1000);
                                    hostToBind = socket.getLocalAddress().getHostAddress();
                                    break;
                                } finally {
                                    try {
                                        socket.close();
                                    } catch (Throwable e) {
                                    }
                                }
                            } catch (Exception e) {
                                logger.warn(e.getMessage(), e);
                            }
                        }
                    }
                    if (isInvalidLocalHost(hostToBind)) {
						/*遍历本地网卡,返回第一个合理的IP*/
                        hostToBind = getLocalHost();
                    }
                }
            }
        }

        map.put(Constants.BIND_IP_KEY, hostToBind);

        /* registry ip,默认不作为bind ip*/
        String hostToRegistry = getValueFromConfig(protocolConfig, Constants.DUBBO_IP_TO_REGISTRY);
        if (hostToRegistry != null && hostToRegistry.length() > 0 && isInvalidLocalHost(hostToRegistry)) {
            throw new IllegalArgumentException("Specified invalid registry ip from property:" + Constants.DUBBO_IP_TO_REGISTRY + ", value:" + hostToRegistry);
        } else if (hostToRegistry == null || hostToRegistry.length() == 0) {
            /* bind ip默认作为registry ip*/
            hostToRegistry = hostToBind;
        }

        map.put(Constants.ANYHOST_KEY, String.valueOf(anyhost));

        return hostToRegistry;
    }

    /**
     * provider注册&监听端口,注册与监听port可独立配置
     * 配置优先级:启动环境变量 -> java命令参数-D -> protocol配置文件port属性配置 -> 协议默认端口
     *
     * @param protocolConfig
     * @param name
     * @return
     */
    private Integer findConfigedPorts(ProtocolConfig protocolConfig, String name, Map<String, String> map) {
        Integer portToBind = null;

        /* 解析环境变量配置的bind port*/
        String port = getValueFromConfig(protocolConfig, Constants.DUBBO_PORT_TO_BIND);
        portToBind = parsePort(port);

        /* 如未通过环境变量配置bind port,则继续按优先级查找*/
        if (portToBind == null) {
            portToBind = protocolConfig.getPort();
            if (provider != null && (portToBind == null || portToBind == 0)) {
                portToBind = provider.getPort();
            }
            final int defaultPort = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(name).getDefaultPort();
            if (portToBind == null || portToBind == 0) {
                portToBind = defaultPort;
            }
			/*如果没有端口则获取一个随机的*/
            if (portToBind == null || portToBind <= 0) {
                portToBind = getRandomPort(name);
                if (portToBind == null || portToBind < 0) {
                    portToBind = getAvailablePort(defaultPort);
                    putRandomPort(name, portToBind);
                }
                logger.warn("Use random available port(" + portToBind + ") for protocol " + name);
            }
        }

        /* 记录bind port,作为url的key*/
        map.put(Constants.BIND_PORT_KEY, String.valueOf(portToBind));

        /* registry port,默认不作为bind port*/
        String portToRegistryStr = getValueFromConfig(protocolConfig, Constants.DUBBO_PORT_TO_REGISTRY);
        Integer portToRegistry = parsePort(portToRegistryStr);
        if (portToRegistry == null) {
            portToRegistry = portToBind;
        }

        return portToRegistry;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值