Curator Zookeeper分布式锁

pom.xml中添加如下配置

<!-- https://mvnrepository.com/artifact/org.apache.curator/curator-recipes -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.10.0</version>
</dependency>

zookeeper配置

下载zookeeper并解压至D:\java\zookeeper-3.4.6

http://www.eu.apache.org/dist/zookeeper/zookeeper-3.4.6/zookeeper-3.4.6.tar.gz

zookeeper配置文件:

zoo-1.cfg

# The number of milliseconds of each tick
tickTime=2000
# The number of ticks that the initial
# synchronization phase can take
initLimit=10
# The number of ticks that can pass between
# sending a request and getting an acknowledgement
syncLimit=5
# the directory where the snapshot is stored.
# do not use /tmp for storage, /tmp here is just
# example sakes.
dataDir=D:/java/zookeeper-3.4.6/data/1
#日志位置
dataLogDir=D:/java/zookeeper-3.4.6/log/1
# the port at which the clients will connect
clientPort=2181
# the maximum number of client connections.
# increase this if you need to handle more clients
#maxClientCnxns=60
#
# Be sure to read the maintenance section of the
# administrator guide before turning on autopurge.
#
# http:/zookeeper.apache.org/doc/current/zookeeperAdmin.html#sc_maintenance
#
# The number of snapshots to retain in dataDir
#autopurge.snapRetainCount=3
# Purge task interval in hours
# Set to "0" to disable auto purge feature
#autopurge.purgeInterval=1
server.1=localhost:2887:3887
server.2=localhost:2888:3888
server.3=localhost:2889:3889

zoo-2.cfgzoo-3.cfg修改如下配置并创建相应的目录

修改clientPort:

zoo-1.cfg:clientPort=2181
zoo-2.cfg:clientPort=2182
zoo-3.cfg:clientPort=2183

创建目录:

zoo-1.cfg:D:/java/zookeeper-3.4.6/data/1
zoo-2.cfg:D:/java/zookeeper-3.4.6/data/2
zoo-3.cfg:D:/java/zookeeper-3.4.6/data/3

分别创建文件:myid,内容分别为各自的id:1、2和3

D:/java/zookeeper-3.4.6/data/1/myid:1
D:/java/zookeeper-3.4.6/data/2/myid:2
D:/java/zookeeper-3.4.6/data/3/myid:3

分别自动各个zookeeper实例

代码测试

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; public class CuratorLockTest {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(5);
String zookeeperConnectionString = "localhost:2181,localhost:2182,localhost:2183";
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client = CuratorFrameworkFactory.newClient(
zookeeperConnectionString, retryPolicy);
client.start();
System.out.println("客户端启动。。。。");
ExecutorService exec = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
exec.submit(new MyLock("client" + i, client, latch));
}
exec.shutdown();
latch.await();
System.out.println("所有任务执行完毕");
client.close();
System.out.println("客户端关闭。。。。");
} static class MyLock implements Runnable {
private String name;
private CuratorFramework client;
private CountDownLatch latch; public MyLock(String name, CuratorFramework client, CountDownLatch latch) {
this.name = name;
this.client = client;
this.latch = latch;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public void run() {
InterProcessMutex lock = new InterProcessMutex(client, "/test_group");
try {
System.out.println("------" + this.name + "---------等待获取锁。--------");
if (lock.acquire(120, TimeUnit.SECONDS)) {
try {
System.out.println("----------" + this.name + "获得资源----------");
System.out.println("----------" + this.name + "正在处理资源----------");
Thread.sleep(10 * 1000);
System.out.println("----------" + this.name + "资源使用完毕----------");
latch.countDown();
} finally {
lock.release();
System.out.println("----------" + this.name + "释放----------");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

运行结果:

客户端启动。。。。
------client1---------等待获取锁。--------
------client2---------等待获取锁。--------
------client0---------等待获取锁。--------
------client4---------等待获取锁。--------
------client3---------等待获取锁。--------
----------client1获得资源----------
----------client1正在处理资源----------
----------client1资源使用完毕----------
----------client1释放----------
----------client3获得资源----------
----------client3正在处理资源----------
----------client3资源使用完毕----------
----------client3释放----------
----------client0获得资源----------
----------client0正在处理资源----------
----------client0资源使用完毕----------
----------client0释放----------
----------client4获得资源----------
----------client4正在处理资源----------
----------client4资源使用完毕----------
----------client4释放----------
----------client2获得资源----------
----------client2正在处理资源----------
----------client2资源使用完毕----------
所有任务执行完毕

参考文档:

Curator Zookeeper分布式锁的更多相关文章

  1. Curator框架实现ZooKeeper分布式锁

    排他锁(X) 这里主要讲讲分布式锁中的排他锁.排他锁(Exclusive Locks,简称X锁),又称为写锁或独占锁,是一种基本的锁类型.如果事务T1对数据对象O1加上了排他锁,那么在整个加锁期间,只 ...

  2. Curator实现zookeeper分布式锁的基本原理

    一.写在前面 之前写过一篇文章(<拜托,面试请不要再问我Redis分布式锁的实现原理>),给大家说了一下Redisson这个开源框架是如何实现Redis分布式锁原理的,这篇文章再给大家聊一 ...

  3. ZooKeeper 分布式锁 Curator 源码 02:可重入锁重复加锁和锁释放

    ZooKeeper 分布式锁 Curator 源码 02:可重入锁重复加锁和锁释放 前言 加锁逻辑已经介绍完毕,那当一个线程重复加锁是如何处理的呢? 锁重入 在上一小节中,可以看到加锁的过程,再回头看 ...

  4. ZooKeeper 分布式锁 Curator 源码 03:可重入锁并发加锁

    前言 在了解了加锁和锁重入之后,最需要了解的还是在分布式场景下或者多线程并发加锁是如何处理的? 并发加锁 先来看结果,在多线程对 /locks/lock_01 加锁时,是在后面又创建了新的临时节点. ...

  5. ZooKeeper 分布式锁 Curator 源码 04:分布式信号量和互斥锁

    前言 分布式信号量,之前在 Redisson 中也介绍过,Redisson 的信号量是将计数维护在 Redis 中的,那现在来看一下 Curator 是如何基于 ZooKeeper 实现信号量的. 使 ...

  6. Zookeeper分布式锁实现Curator十一问

    前面我们剖析了Redisson的源码,主要分析了Redisson实现Redis分布式锁的15问,理清了Redisson是如何实现的分布式锁和一些其它的特性.这篇文章就来接着剖析Zookeeper分布式 ...

  7. 女朋友也能看懂的Zookeeper分布式锁原理

      前言 关于分布式锁,在互联网行业的使用场景还是比较多的,比如电商的库存扣减,秒杀活动,集群定时任务执行等需要进程互斥的场景.而实现分布式锁的手段也很多,大家比较常见的就是redis跟zookeep ...

  8. 分布式锁(一) Zookeeper分布式锁

    什么是Zookeeper? Zookeeper(业界简称zk)是一种提供配置管理.分布式协同以及命名的中心化服务,这些提供的功能都是分布式系统中非常底层且必不可少的基本功能,但是如果自己实现这些功能而 ...

  9. ZooKeeper 分布式锁

    在Redis分布式锁一文中, 作者介绍了如何使用Redis开发分布式锁. Redis分布式锁具有轻量高吞吐量的特点,但是一致性保证较弱.我们可以使用Zookeeper开发分布式锁,来满足对高一致性的要 ...

随机推荐

  1. 【WPF】释放图像资源, [删除时报另一进程占用]

    源:zhantianyou CODE private BitmapImage ReturnBitmap(string destFile) { // Read byte[] from png file ...

  2. celery 框架

    转自:http://www.cnblogs.com/forward-wang/p/5970806.html 生产者消费者模式 在实际的软件开发过程中,经常会碰到如下场景:某个模块负责产生数据,这些数据 ...

  3. idea 如何隐藏/展示不想看到的文件

    隐藏:在 Ignore files and folders中添加想要过滤的文件或文件夹名称 展示隐藏文件: 在过滤列表中删除掉文件或者文件夹就好了

  4. 【BZOJ 1016】【JSOI 2008】最小生成树计数

    http://www.lydsy.com/JudgeOnline/problem.php?id=1016 统计每一个边权在最小生成树中使用的次数,这个次数在任何一个最小生成树中都是固定的(归纳证明). ...

  5. --关于null在oracle数据库中是否参与计算,进行验证,

    --关于null在oracle数据库中是否参与计算,进行验证,with td as (select null id,1 name from dual ),td1 as ( select null id ...

  6. Android 和 H5 通信

    有需要与h5通信的需求,写了一个helper类,处理与h5通信. import android.content.Context; import android.os.Handler; import a ...

  7. Ubuntu中配置Java环境变量时,出现command not found问题解决记录

    百度出Ubuntu中配置Java环境变量时,在利用sudo gedit /etc/profile 对profile编辑后, 在terminal中输入 sudo source /etc/profile, ...

  8. COGS 2533. [HZOI 2016]小鱼之美

    我们可以发现所有的操作当中,只有坐标的增加,没有坐标的减少. 所以我们可以发现这么一个简单的事实,一条鱼一旦出了渔网,那么它就不可能再回来. 但是目前这并没有什么卵用. 我们可以把询问一个矩阵当中的鱼 ...

  9. 【JavaWeb】Spring+SpringMVC+MyBatis+SpringSecurity+EhCache+JCaptcha 完整Web基础框架(三)

    Spring+SpringMVC MVC呢,现在似乎越来越流行使用SpringMVC框架,我自己用的感觉,是非常好,确实很舒服,配置一开始是麻烦了一点点,但是后续的开发真的是很清爽! SpringMV ...

  10. ThinkPhp 3.2 常见问题与注意事项

    1 命名空间声明必须写在脚本的最前面 如果运行PHP脚本后出现如下错误: Namespace declaration statement has to be the very first statem ...