dubbo源码分析-dubbo-registry-zookeeper

dubbo-registry-zookeeper非常简单,只有两个类。
dubbo源码分析-dubbo-registry-zookeeper_第1张图片

ZookeeperRegistryFactory


package org.apache.dubbo.registry.zookeeper;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.support.AbstractRegistryFactory;
import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter;

/**
 * ZookeeperRegistryFactory.
 * 工厂类
 */
public class ZookeeperRegistryFactory extends AbstractRegistryFactory {

    private ZookeeperTransporter zookeeperTransporter;

    public void setZookeeperTransporter(ZookeeperTransporter zookeeperTransporter) {
        this.zookeeperTransporter = zookeeperTransporter;
    }

    @Override
    public Registry createRegistry(URL url) {
        // 返回ZookeeperRegistry实例
        return new ZookeeperRegistry(url, zookeeperTransporter);
    }

}

ZookeeperRegistry

红框中是ZookeeperRegistry的重要方法
dubbo源码分析-dubbo-registry-zookeeper_第2张图片

    // 构造器
    public ZookeeperRegistry(URL url, ZookeeperTransporter zookeeperTransporter) {
        super(url);
        if (url.isAnyHost()) {
            throw new IllegalStateException("registry address == null");
        }
        // 获取group,默认值是: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;
        // 获取zkClient
        zkClient = zookeeperTransporter.connect(url);
        // 添加zkClient监听
        zkClient.addStateListener(new StateListener() {
            @Override
            public void stateChanged(int state) {
                // 若重连,则恢复。
                if (state == RECONNECTED) {
                    try {
                        recover();
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }
                }
            }
        });
    }
    // 注册
    @Override
    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);
        }
    }
    // 移除注册
    @Override
    protected void doUnregister(URL url) {
        try {
            zkClient.delete(toUrlPath(url));
        } catch (Throwable e) {
            throw new RpcException("Failed to unregister " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e);
        }
    }

你可能感兴趣的:(dubbo)