Fork me on GitHub

Curator实现ZooKeeper分布式锁源码

3. Curator源码

上一篇文章,基于ZooKeeper的分布式锁 已经讲了原理和使用了。接下来我们来看看 Curator 实现分布式锁的源码。

再贴上我们的实现代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class CuratorTest {
public static void main(String[] args) throws Exception {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client = CuratorFrameworkFactory.newClient(
"127.0.0.1:2181",
retryPolicy);
client.start();

InterProcessMutex lock = new InterProcessMutex(client, "/distribute_lock/product01_lock");
lock.acquire();
try {
// 执行业务逻辑,这里停30秒,为了看效果
Thread.sleep(30000L);
} finally {
lock.release();
}
}
}

我们先从第 9 行代码说起,InterProcessMutex 是什么呢?为什么我们选择它来加锁和解锁呢?

来,上源码:

1
2
3
4
5
6
/**
* A re-entrant mutex that works across JVMs. Uses Zookeeper to hold the lock. All processes in all JVMs that
* use the same lock path will achieve an inter-process critical section. Further, this mutex is
* "fair" - each user will get the mutex in the order requested (from ZK's point of view)
*/
public class InterProcessMutex implements InterProcessLock, Revocable<InterProcessMutex>

翻译一下 InterProcessMutex 的注释:

在 JVM 的运行过程中,是可重入的,并且是互斥的。通过 Zookeeper 获得这把锁,在使用的 JVM 进程中,只要是用的同一个锁路径的线程,都会获取到进程间的临界区资源。更进一步地说,这个互斥锁是公平的,每一个线程都会根据请求的顺序最终获取锁。

总结一下很简单,这是个可重入互斥锁,并且是公平锁。有点多线程基础的同学应该知道公平锁是什么意思。

23:56:52.011 [main-SendThread(127.0.0.1:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Reading reply sessionid:0x100b887615d0028, packet:: clientPath:null serverPath:null finished:false header:: 11,1 replyHeader:: 11,207,0 request:: ‘/distribute_lock/product01_lock/_c_84fb3903-14c4-40fe-ac80-322820dfec37-lock-,#3139322e3136382e3130312e3231,v{s{31,s{‘world,’anyone}}},3 response:: ‘/distribute_lock/product01_lock/_c_84fb3903-14c4-40fe-ac80-322820dfec37-lock-0000000000

本文标题:Curator实现ZooKeeper分布式锁源码

原始链接:https://zhaoxiaofa.com/2019/08/30/Curator实现ZooKeeper分布式锁源码/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。