分布式系统中经常需要协调多进程,多个jvm,或者多台机器之间的同步问题,得益于zookeeper,实现了一个分布式的共享锁,方便在多台服务器之间竞争资源时,来协调各系统之间的协作和同步。
package com.zookeeper.lock.server; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.Stat; /** DistributedLock lock = null; try { lock = new DistributedLock("127.0.0.1:2182","test"); lock.lock(); //do something... } catch (Exception e) { e.printStackTrace(); } finally { if(lock != null) lock.unlock(); } * @author xueliang * */ public class DistributedLock implements Lock, Watcher{ private ZooKeeper zk; private String root = "/locks";//根 private String lockName;//竞争资源的标志 private String waitNode;//等待前一个锁 private String myZnode;//当前锁 private CountDownLatch latch;//计数器 private int sessionTimeout = 30000; private List<Exception> exception = new ArrayList<Exception>(); /** * 创建分布式锁,使用前请确认config配置的zookeeper服务可用 * @param config 127.0.0.1:2181 * @param lockName 竞争资源标志,lockName中不能包含单词lock */ public DistributedLock(String config, String lockName){ this.lockName = lockName; // 创建一个与服务器的连接 try { zk = new ZooKeeper(config, sessionTimeout, this); Stat stat = zk.exists(root, false); if(stat == null){ // 创建根节点 zk.create(root, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT); } } catch (IOException e) { exception.add(e); } catch (KeeperException e) { exception.add(e); } catch (InterruptedException e) { exception.add(e); } } /** * zookeeper节点的监视器 */ public void process(WatchedEvent event) { if(this.latch != null) { this.latch.countDown(); } } public void lock() { if(exception.size() > 0){ throw new LockException(exception.get(0)); } try { if(this.tryLock()){ System.out.println("Thread " + Thread.currentThread().getId() + " " +myZnode + " get lock true"); return; } else{ waitForLock(waitNode, sessionTimeout);//等待锁 } } catch (KeeperException e) { throw new LockException(e); } catch (InterruptedException e) { throw new LockException(e); } } public boolean tryLock() { try { String splitStr = "_lock_"; if(lockName.contains(splitStr)) throw new LockException("lockName can not contains \\u000B"); //创建临时子节点 myZnode = zk.create(root + "/" + lockName + splitStr, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL); System.out.println(myZnode + " is created "); //取出所有子节点 List<String> subNodes = zk.getChildren(root, false); //取出所有lockName的锁 List<String> lockObjNodes = new ArrayList<String>(); for (String node : subNodes) { String _node = node.split(splitStr)[0]; if(_node.equals(lockName)){ lockObjNodes.add(node); } } Collections.sort(lockObjNodes); System.out.println(myZnode + "==" + lockObjNodes.get(0)); if(myZnode.equals(root+"/"+lockObjNodes.get(0))){ //如果是最小的节点,则表示取得锁 return true; } //如果不是最小的节点,找到比自己小1的节点 String subMyZnode = myZnode.substring(myZnode.lastIndexOf("/") + 1); waitNode = lockObjNodes.get(Collections.binarySearch(lockObjNodes, subMyZnode) - 1); } catch (KeeperException e) { throw new LockException(e); } catch (InterruptedException e) { throw new LockException(e); } return false; } public boolean tryLock(long time, TimeUnit unit) { try { if(this.tryLock()){ return true; } return waitForLock(waitNode,time); } catch (Exception e) { e.printStackTrace(); } return false; } private boolean waitForLock(String lower, long waitTime) throws InterruptedException, KeeperException { Stat stat = zk.exists(root + "/" + lower,true); //判断比自己小一个数的节点是否存在,如果不存在则无需等待锁,同时注册监听 if(stat != null){ System.out.println("Thread " + Thread.currentThread().getId() + " waiting for " + root + "/" + lower); this.latch = new CountDownLatch(1); this.latch.await(waitTime, TimeUnit.MILLISECONDS); this.latch = null; } return true; } public void unlock() { try { System.out.println("unlock " + myZnode); zk.delete(myZnode,-1); myZnode = null; zk.close(); } catch (InterruptedException e) { e.printStackTrace(); } catch (KeeperException e) { e.printStackTrace(); } } public void lockInterruptibly() throws InterruptedException { this.lock(); } public Condition newCondition() { return null; } public class LockException extends RuntimeException { private static final long serialVersionUID = 1L; public LockException(String e){ super(e); } public LockException(Exception e){ super(e); } } }
package com.zookeeper.lock.client; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; /** ConcurrentTask[] task = new ConcurrentTask[5]; for(int i=0;i<task.length;i++){ task[i] = new ConcurrentTask(){ public void run() { System.out.println("=============="); }}; } new ConcurrentTest(task); * @author xueliang * */ public class ConcurrentClient { private CountDownLatch startSignal = new CountDownLatch(1);//开始阀门 private CountDownLatch doneSignal = null;//结束阀门 private CopyOnWriteArrayList<Long> list = new CopyOnWriteArrayList<Long>(); private AtomicInteger err = new AtomicInteger();//原子递增 private ConcurrentTask[] task = null; public ConcurrentClient(ConcurrentTask... task){ this.task = task; if(task == null){ System.out.println("task can not null"); System.exit(1); } doneSignal = new CountDownLatch(task.length); start(); } /** * @param args * @throws ClassNotFoundException */ private void start(){ //创建线程,并将所有线程等待在阀门处 createThread(); //打开阀门 startSignal.countDown();//递减锁存器的计数,如果计数到达零,则释放所有等待的线程 try { doneSignal.await();//等待所有线程都执行完毕 } catch (InterruptedException e) { e.printStackTrace(); } //计算执行时间 getExeTime(); } /** * 初始化所有线程,并在阀门处等待 */ private void createThread() { long len = doneSignal.getCount(); for (int i = 0; i < len; i++) { final int j = i; new Thread(new Runnable(){ public void run() { try { startSignal.await();//使当前线程在锁存器倒计数至零之前一直等待 long start = System.currentTimeMillis(); task[j].run(); long end = (System.currentTimeMillis() - start); list.add(end); } catch (Exception e) { err.getAndIncrement();//相当于err++ } doneSignal.countDown(); } }).start(); } } /** * 计算平均响应时间 */ private void getExeTime() { int size = list.size(); List<Long> _list = new ArrayList<Long>(size); _list.addAll(list); Collections.sort(_list); long min = _list.get(0); long max = _list.get(size-1); long sum = 0L; for (Long t : _list) { sum += t; } long avg = sum/size; System.out.println("min: " + min); System.out.println("max: " + max); System.out.println("avg: " + avg); System.out.println("err: " + err.get()); } public interface ConcurrentTask { void run(); } }
package com.zookeeper.lock.test; import com.zookeeper.lock.client.ConcurrentClient; import com.zookeeper.lock.client.ConcurrentClient.ConcurrentTask; import com.zookeeper.lock.server.DistributedLock; public class Test { public static void main(String[] args) { Runnable task1 = new Runnable(){ public void run() { DistributedLock lock = null; try { lock = new DistributedLock("127.0.0.1:2182","test1"); //lock = new DistributedLock("127.0.0.1:2182","test2"); lock.lock(); Thread.sleep(3000); System.out.println("===Thread " + Thread.currentThread().getId() + " running"); } catch (Exception e) { e.printStackTrace(); } finally { if(lock != null) lock.unlock(); } } }; new Thread(task1).start(); try { Thread.sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); } ConcurrentTask[] tasks = new ConcurrentTask[5]; for(int i=0;i<tasks.length;i++){ ConcurrentTask task3 = new ConcurrentTask(){ public void run() { DistributedLock lock = null; try { lock = new DistributedLock("127.0.0.1:2181","test2"); lock.lock(); System.out.println("Thread " + Thread.currentThread().getId() + " running"); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } }; tasks[i] = task3; } new ConcurrentClient(tasks); } }
测试结果:
/locks/test1_lock_0000004356 is created /locks/test1_lock_0000004356==test1_lock_0000004356 Thread 8 /locks/test1_lock_0000004356 get lock true /locks/test2_lock_0000004357 is created /locks/test2_lock_0000004359 is created /locks/test2_lock_0000004358 is created /locks/test2_lock_0000004363 is created /locks/test2_lock_0000004361 is created /locks/test2_lock_0000004360 is created /locks/test2_lock_0000004362 is created /locks/test2_lock_0000004366 is created /locks/test2_lock_0000004365 is created /locks/test2_lock_0000004364 is created /locks/test2_lock_0000004357==test2_lock_0000004357 Thread 14 /locks/test2_lock_0000004357 get lock true Thread 14 running unlock /locks/test2_lock_0000004357 /locks/test2_lock_0000004358==test2_lock_0000004357 /locks/test2_lock_0000004361==test2_lock_0000004357 /locks/test2_lock_0000004359==test2_lock_0000004357 /locks/test2_lock_0000004362==test2_lock_0000004357 Thread 12 waiting for /locks/test2_lock_0000004360 /locks/test2_lock_0000004366==test2_lock_0000004357 Thread 18 waiting for /locks/test2_lock_0000004357 /locks/test2_lock_0000004363==test2_lock_0000004357 Thread 18 running unlock /locks/test2_lock_0000004358 Thread 13 waiting for /locks/test2_lock_0000004362 /locks/test2_lock_0000004365==test2_lock_0000004358 Thread 16 waiting for /locks/test2_lock_0000004361 Thread 19 waiting for /locks/test2_lock_0000004358 /locks/test2_lock_0000004360==test2_lock_0000004358 Thread 15 waiting for /locks/test2_lock_0000004365 /locks/test2_lock_0000004364==test2_lock_0000004358 Thread 11 waiting for /locks/test2_lock_0000004364 Thread 20 waiting for /locks/test2_lock_0000004359 Thread 19 running unlock /locks/test2_lock_0000004359 Thread 17 waiting for /locks/test2_lock_0000004363 Thread 20 running unlock /locks/test2_lock_0000004360 Thread 12 running unlock /locks/test2_lock_0000004361 Thread 16 running unlock /locks/test2_lock_0000004362 Thread 13 running unlock /locks/test2_lock_0000004363 Thread 17 running unlock /locks/test2_lock_0000004364 Thread 11 running unlock /locks/test2_lock_0000004365 Thread 15 running unlock /locks/test2_lock_0000004366 min: 506 max: 1481 avg: 968 err: 0 ===Thread 8 running unlock /locks/test1_lock_0000004356
关于zookeeper的很好的文章:
https://www.ibm.com/developerworks/cn/opensource/os-cn-zookeeper/
这个分布式共享锁就是参考这篇文章实现的。
来自:http://my.oschina.net/shenxueliang/blog/135865
相关推荐
- **测试代码**:展示了如何在实际应用中使用Zookeeper实现分布式锁的示例,包括创建锁、获取锁、释放锁以及异常处理等操作。 - **实用工具类**:封装了与Zookeeper交互的常用方法,如创建节点、设置监听、检查节点...
4. **锁节点的创建与检查:** 示例代码中创建了两个锁节点`/ExclusiveLockDemo`和`/ShardLockDemo`,分别用于实现非共享和共享锁。 5. **锁的等待机制:** `CountDownLatch`被用来阻塞锁获取操作,直到监听到锁可用...
分布式全局锁是分布式系统中一个重要的同步控制工具,它允许在多节点环境下,对共享资源进行独占式访问,防止并发问题。Zookeeper,作为Apache的一个高性能、高可用的分布式协调服务,常被用于实现这样的功能。在这...
在分布式系统中,数据一致性是至关重要的,而实现这一目标的一种常见方法是使用分布式锁。本文将深入探讨基于Zookeeper实现的分布式读写锁,并利用Zkclient客户端进行操作。Zookeeper是一个分布式服务协调框架,它...
在实际项目中,可以使用Java的ZooKeeper客户端库(如Curator)来简化分布式锁的实现。这些库提供了高级API,帮助开发者更方便地处理ZooKeeper的操作,例如创建、删除节点,以及设置节点监视器等。 总之,ZooKeeper...
本文将详细讲解如何使用Java与Apache ZooKeeper实现一个分布式锁的示例。 ZooKeeper是一个分布式协调服务,它提供了一种可靠的方式来管理和同步分布式系统的数据。在分布式锁的场景中,ZooKeeper可以作为一个中心化...
**Zookeeper的分布式锁实现原理** 1. **节点创建与监视**: Zookeeper允许客户端创建临时节点,这些节点会在客户端断开连接时自动删除。分布式锁的实现通常会为每个请求创建一个临时顺序节点,按照创建的顺序形成一...
在这个场景下,我们将关注ZooKeeper如何实现分布式锁,特别是不可重入锁、可重入锁以及可重入读写锁的概念与实践。 首先,我们要理解什么是分布式锁。在多节点并发访问共享资源时,分布式锁能确保同一时刻只有一个...
Zookeeper的核心理念是通过一个中心化的服务器集群来维护共享状态,使得分布式系统中的各个节点可以高效、一致地获取和更新数据。它基于一个叫做ZNode的数据结构模型,每个ZNode都是一个路径,可以存储数据,并且...
Zookeeper 实现分布式锁是指使用 Zookeeper 来管理分布式环境中的共享资源,实现互斥访问,以保证数据的一致性。 分布式锁的介绍 分布式锁是指在分布式环境中保护跨进程、跨主机、跨网络的共享资源,实现互斥...
在Zookeeper中,可以通过创建多个顺序节点来实现,每个读请求创建一个节点,所有读请求节点共享锁。 2. **互斥锁(写锁)**:只允许一个线程写入,不允许读取和其他写入。这与排他锁类似,通过创建临时节点并监听...
如何操作Redis和zookeeper实现分布式锁 在分布式场景下,有很多种情况都需要实现最终一致性。在设计远程上下文的领域事件的时候,为了保证最终一致性,在通过领域事件进行通讯的方式中,可以共享存储(领域模型和...
在Spring XD中使用ZooKeeper可以实现分布式环境下的协调,例如在集群中管理服务的分布和任务分配。 对于领导者选举,ZooKeeper提供了一种无需羊群效应(Herd Effect)的锁机制。这种锁的实现依赖于临时顺序节点的...
ZooKeeper是一个广泛使用的分布式锁实现方案,本文将对ZooKeeper分布式锁进行详细的介绍。 什么是分布式锁 分布式锁是指在分布式系统中,多个节点之间对共享资源的访问控制机制。分布式锁可以确保在分布式环境中,...
通过深入理解Zookeeper的工作原理以及ZookeeperNet库的使用,开发者可以有效地在C#环境中实现高可用的分布式锁,保障多节点之间的协同工作和数据一致性。在实际项目中,分布式锁可以广泛应用于数据库操作、并发任务...
4. **分布式锁**:ZooKeeper可以实现分布式锁,确保在多线程或分布式环境下,对共享资源的访问有序且互斥。 5. **领导者选举**:ZooKeeper的ZAB协议可以用于分布式环境中的领导者选举,确保集群的高可用性。 **三...
分布式锁是一种在分布式系统中实现同步的技术,它允许多个节点在同一时间访问共享资源。在大型分布式环境中,确保数据的一致性和正确性至关重要,这就是分布式锁发挥作用的地方。Zookeeper,一个由Apache开发的...
- **分布式锁**:通过特定的ZNode结构,实现共享锁服务。 - **队列服务**:FIFO(先进先出)的队列可以通过ZNode的顺序创建实现。 3. **ZooKeeper的架构** - **客户端-服务器模型**:每个客户端连接到一个或多个...
分布式锁用于在多个进程中控制对共享资源的访问;主选举是确定集群中某个角色的唯一领导者。 书中详细介绍了ZooKeeper的数据模型,这是一个层次化的命名空间,类似于文件系统,由节点(ZNode)构成,每个节点可以...