InterProcessMutex
实现的分布式锁,每个线程对应的节点名类似下面的格式:
说明:
- 第
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-";