Open Source, Open Future!
  menu
107 文章
ღゝ◡╹)ノ❤️

Zookeeper---Curator---分布式锁名称生成规则

InterProcessMutex实现的分布式锁,每个线程对应的节点名类似下面的格式:
image.png
说明:

  • 1块:PROTECTED_PREFIX
  • 2块:protectedId (UUID)
  • 3块:LOCK_NAME
  • 4块:zk自动生成的顺序号

对应的源码如下:

ourPath=client.create().creatingParentsIfNeeded().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(path);   

creatingParentsIfNeeded:当父节点不存在时,会自动创建父节点
withProtection源码如下:

    @Override
    public ACLCreateModeBackgroundPathAndBytesable<String> withProtection()
    {
          return CreateBuilderImpl.this.withProtection();
    }
    @Override
    public ACLCreateModeBackgroundPathAndBytesable<String> withProtection()
    {
        setProtected();
        return this;
    }
    private void setProtected()
    {
        doProtected = true;
        protectedId = UUID.randomUUID().toString();
    }

生成UUID赋予CreateBuilderImpl对象的属性protectedId
withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(path):指定创建的节点为临时有序节点;
forPath源码如下:

    @Override
    public String forPath(String path) throws Exception
    {
        return forPath(path, client.getDefaultData());
    }
    @Override
    public String forPath(final String givenPath, byte[] data) throws Exception
    {
        if ( compress )
        {
            data = client.getCompressionProvider().compress(givenPath, data);
        }
        final String adjustedPath = adjustPath(client.fixForNamespace(givenPath));
        String returnPath = null;
        if ( backgrounding.inBackground() )
        {
            pathInBackground(adjustedPath, data, givenPath);
        }
        else
        {
            String path = protectedPathInForeground(adjustedPath, data);
            returnPath = client.unfixForNamespace(path);
        }
        return returnPath;
    }

forPath中调用adjustPath,源码如下:

    private String adjustPath(String path) throws Exception
    {
        if ( doProtected )
        {
            ZKPaths.PathAndNode pathAndNode = ZKPaths.getPathAndNode(path);
            String name = getProtectedPrefix(protectedId) + pathAndNode.getNode();
            path = ZKPaths.makePath(pathAndNode.getPath(), name);
        }
        return path;
    }

getProtectedPrefix源码如下:

    private static String getProtectedPrefix(String protectedId)
    {
        return PROTECTED_PREFIX + protectedId + "-";
    }

static final String PROTECTED_PREFIX = "_c_";

pathAndNode.getNode()获取的值为LOCK_NAME:
private static final String LOCK_NAME = "lock-";

相关链接

Zookeeper---Curator---分布式锁源码分析