`
chenkangxian
  • 浏览: 87622 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

zookeeper下的分布式锁

阅读更多

 

zookeeperhadoop下面的一个子项目, 用来进行分布式系统之间的相互协调。

zookeeper源码包的recipe目录下有一个互斥锁lock的实现范例,笔者对其简要包装,以便看起来更为明了:

 

package org.apache.zookeeper.recipes.lock;

import java.io.IOException;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

public class DistributedLock {

	private WriteLock lock;
	private String lockPath = "/lock";
	private ZooKeeper zooKeeper ;

	public DistributedLock(ZooKeeper zooKeeper){
		this.zooKeeper = zooKeeper;
	}

	/**
	 * 获得锁
	 * 
	 * Author:  chenkangxian
	 *
	 * Last Modification Time: 2012-4-6
	 *
	 * @return 获得锁是否成功
	 */
	public boolean lock(){
		lock = new WriteLock(zooKeeper, lockPath, null);
		try {
			while (true) {
				if (lock.lock()) {
					return true;
				}

			}
		} catch (KeeperException e) {
			e.printStackTrace();
			return false;
		} catch (InterruptedException e) {
			e.printStackTrace();
			return false;
		}

	}

	/**
	 * 解锁
	 * 
	 * Author:  chenkangxian
	 *
	 * Last Modification Time: 2012-4-6
	 *
	 */
	public void unlock(){
		lock.unlock();
	}
	
	public static void main(String args[]){

		try {
			Watcher wh=new Watcher(){
				public void process(org.apache.zookeeper.WatchedEvent event)
				{
					System.out.println(event.toString());
				}
			};

			ZooKeeper zooKeeper = new ZooKeeper("localhost:2181", 20000, wh);
			final DistributedLock distributedLock = new DistributedLock(zooKeeper);
			
			for(int i = 0; i < 100 ; i ++){
				Thread thread = new Thread(new Runnable(){
					
					@Override
					public void run() {
						if(distributedLock.lock()){
							System.out.println("获得锁---------------");
							
						}

						distributedLock.unlock();
						
					}
					
				});
			}

			Thread.sleep(2000*1000);

		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}
}

 

 

WirteLock实现:

 

 

package org.apache.zookeeper.recipes.lock;

import org.apache.log4j.Logger;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import static org.apache.zookeeper.CreateMode.EPHEMERAL_SEQUENTIAL;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;

import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;



public class WriteLock extends ProtocolSupport {
    private static final Logger LOG = Logger.getLogger(WriteLock.class);

    private final String dir;
    private String id;
    private ZNodeName idName;
    private String ownerId;
    private String lastChildId;
    private byte[] data = {0x12, 0x34};
    private LockListener callback;
    private LockZooKeeperOperation zop;
    
    /**
     * zookeeper contructor for writelock
     * @param zookeeper zookeeper client instance
     * @param dir the parent path you want to use for locking
     * @param acls the acls that you want to use for all the paths, 
     * if null world read/write is used.
     */
    public WriteLock(ZooKeeper zookeeper, String dir, List<ACL> acl) {
        super(zookeeper);
        this.dir = dir;
        if (acl != null) {
            setAcl(acl);
        }
        this.zop = new LockZooKeeperOperation();
    }
    
    /**
     * zookeeper contructor for writelock with callback
     * @param zookeeper the zookeeper client instance
     * @param dir the parent path you want to use for locking
     * @param acl the acls that you want to use for all the paths
     * @param callback the call back instance
     */
    public WriteLock(ZooKeeper zookeeper, String dir, List<ACL> acl, 
            LockListener callback) {
        this(zookeeper, dir, acl);
        this.callback = callback;
    }

    /**
     * return the current locklistener
     * @return the locklistener
     */
    public LockListener getLockListener() {
        return this.callback;
    }
    
    /**
     * register a different call back listener
     * @param callback the call back instance
     */
    public void setLockListener(LockListener callback) {
        this.callback = callback;
    }

    /**
     * Removes the lock or associated znode if 
     * you no longer require the lock. this also 
     * removes your request in the queue for locking
     * in case you do not already hold the lock.
     * @throws RuntimeException throws a runtime exception
     * if it cannot connect to zookeeper.
     */
    public synchronized void unlock() throws RuntimeException {
        
        if (!isClosed() && id != null) {
            // we don't need to retry this operation in the case of failure
            // as ZK will remove ephemeral files and we don't wanna hang
            // this process when closing if we cannot reconnect to ZK
            try {
                
                ZooKeeperOperation zopdel = new ZooKeeperOperation() {
                    public boolean execute() throws KeeperException,
                        InterruptedException {
                        zookeeper.delete(id, -1);   
                        return Boolean.TRUE;
                    }
                };
                zopdel.execute();
            } catch (InterruptedException e) {
                LOG.warn("Caught: " + e, e);
                //set that we have been interrupted.
               Thread.currentThread().interrupt();
            } catch (KeeperException.NoNodeException e) {
                // do nothing
            } catch (KeeperException e) {
                LOG.warn("Caught: " + e, e);
                throw (RuntimeException) new RuntimeException(e.getMessage()).
                    initCause(e);
            }
            finally {
                if (callback != null) {
                    callback.lockReleased();
                }
                id = null;
            }
        }
    }
    
    /** 
     * the watcher called on  
     * getting watch while watching 
     * my predecessor
     */
    private class LockWatcher implements Watcher {
        public void process(WatchedEvent event) {
            // lets either become the leader or watch the new/updated node
            LOG.debug("Watcher fired on path: " + event.getPath() + " state: " + 
                    event.getState() + " type " + event.getType());
            try {
                lock();
            } catch (Exception e) {
                LOG.warn("Failed to acquire lock: " + e, e);
            }
        }
    }
    
    /**
     * a zoookeeper operation that is mainly responsible
     * for all the magic required for locking.
     */
    private  class LockZooKeeperOperation implements ZooKeeperOperation {
        
        /** find if we have been created earler if not create our node
         * 
         * @param prefix the prefix node
         * @param zookeeper teh zookeeper client
         * @param dir the dir paretn
         * @throws KeeperException
         * @throws InterruptedException
         */
        private void findPrefixInChildren(String prefix, ZooKeeper zookeeper, String dir) 
            throws KeeperException, InterruptedException {
            List<String> names = zookeeper.getChildren(dir, false);
            for (String name : names) {
                if (name.startsWith(prefix)) {
                    id = name;
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Found id created last time: " + id);
                    }
                    break;
                }
            }
            if (id == null) {
                id = zookeeper.create(dir + "/" + prefix, data, 
                        getAcl(), EPHEMERAL_SEQUENTIAL);

                if (LOG.isDebugEnabled()) {
                    LOG.debug("Created id: " + id);
                }
            }

        }
        
        /**
         * the command that is run and retried for actually 
         * obtaining the lock
         * @return if the command was successful or not
         */
        public boolean execute() throws KeeperException, InterruptedException {
            do {
                if (id == null) {
                    long sessionId = zookeeper.getSessionId();
                    String prefix = "x-" + sessionId + "-";
                    // lets try look up the current ID if we failed 
                    // in the middle of creating the znode
                    findPrefixInChildren(prefix, zookeeper, dir);
                    idName = new ZNodeName(id);
                }
                if (id != null) {
                    List<String> names = zookeeper.getChildren(dir, false);
                    if (names.isEmpty()) {
                        LOG.warn("No children in: " + dir + " when we've just " +
                        "created one! Lets recreate it...");
                        // lets force the recreation of the id
                        id = null;
                    } else {
                        // lets sort them explicitly (though they do seem to come back in order ususally :)
                        SortedSet<ZNodeName> sortedNames = new TreeSet<ZNodeName>();
                        for (String name : names) {
                            sortedNames.add(new ZNodeName(dir + "/" + name));
                        }
                        ownerId = sortedNames.first().getName();
                        SortedSet<ZNodeName> lessThanMe = sortedNames.headSet(idName);
                        if (!lessThanMe.isEmpty()) {
                            ZNodeName lastChildName = lessThanMe.last();
                            lastChildId = lastChildName.getName();
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("watching less than me node: " + lastChildId);
                            }
                            Stat stat = zookeeper.exists(lastChildId, new LockWatcher());
                            if (stat != null) {
                                return Boolean.FALSE;
                            } else {
                                LOG.warn("Could not find the" +
                                		" stats for less than me: " + lastChildName.getName());
                            }
                        } else {
                            if (isOwner()) {
                                if (callback != null) {
                                    callback.lockAcquired();
                                }
                                return Boolean.TRUE;
                            }
                        }
                    }
                }
            }
            while (id == null);
            return Boolean.FALSE;
        }
    };

    /**
     * Attempts to acquire the exclusive write lock returning whether or not it was
     * acquired. Note that the exclusive lock may be acquired some time later after
     * this method has been invoked due to the current lock owner going away.
     */
    public synchronized boolean lock() throws KeeperException, InterruptedException {
        if (isClosed()) {
            return false;
        }
        ensurePathExists(dir);

        return (Boolean) retryOperation(zop);
    }

    /**
     * return the parent dir for lock
     * @return the parent dir used for locks.
     */
    public String getDir() {
        return dir;
    }

    /**
     * Returns true if this node is the owner of the
     *  lock (or the leader)
     */
    public boolean isOwner() {
        return id != null && ownerId != null && id.equals(ownerId);
    }

    /**
     * return the id for this lock
     * @return the id for this lock
     */
    public String getId() {
       return this.id;
    }
}
分享到:
评论

相关推荐

    基于zookeeper的分布式锁简单实现

    这时,Zookeeper,一个高可用的分布式协调服务,常被用来实现分布式锁。 Zookeeper由Apache基金会开发,它提供了一种可靠的分布式一致性服务,包括命名服务、配置管理、集群同步、领导者选举等功能。Zookeeper基于...

    使用ZooKeeper实现分布式锁

    在处理订单生成的场景中,我们可以这样应用ZooKeeper分布式锁: 1. 当用户发起订单请求时,服务端会尝试在ZooKeeper上创建一个临时顺序节点。 2. 如果创建成功,服务端会检查当前最小序号的节点是否是自己创建的。...

    基于zookeeper的分布式锁实现demo

    **Zookeeper分布式锁的关键特性包括:** 1. **顺序一致性:** Zookeeper中的节点被创建顺序是全局唯一的,这有助于实现锁的唯一性。 2. **原子性:** 创建和删除节点的操作在Zookeeper中都是原子性的,这保证了...

    zookeeper做分布式锁

    分布式锁是解决多节点系统中同步问题的一种常见技术,ZooKeeper,由Apache基金会开发的分布式协调服务,常被用于实现高效可靠的分布式锁。本文将深入探讨如何利用ZooKeeper来构建分布式锁,并讨论其背后的关键概念和...

    基于zookeeper实现分布式锁

    zooKeeper是一个分布式的,开放源码的分布式应用程序协调服务,是集群的管理者。提供了文件系统和通知机制。...在开发项目的过程中,很多大型项目都是分布式部署的,那么我们现在使用zookeeper实现一个分布式锁。

    ZooKeeper-分布式过程协同技术详解 和从Paxos到Zookeeper

    书中还详细介绍了ZooKeeper的应用场景,如命名服务、配置管理、集群管理、分布式锁等。在命名服务中,ZooKeeper可以作为一个全局的名字注册表,使得分布式系统中的组件可以找到彼此。配置管理则允许系统动态更新配置...

    从Paxos到Zookeeper分布式一致性原理与实践 + ZooKeeper-分布式过程协同技术详解 pdf

    《从Paxos到Zookeeper分布式一致性原理与实践》与《ZooKeeper-分布式过程协同技术详解》这两本书深入探讨了分布式系统中的一个重要概念——一致性,以及如何通过ZooKeeper这一工具来实现高效的分布式协同。...

    使用zookeeper实现分布式共享锁

    Zookeeper的分布式锁主要基于两种数据结构:临时节点(ephemeral nodes)和顺序节点(sequential nodes)。 首先,临时节点是当客户端断开连接时会被自动删除的节点。这种特性使得Zookeeper可以检测到节点的存活...

    zookeeper实现分布式锁

    在程序开发过程中不得不考虑的就是并发问题。在java中对于同一个jvm而言,jdk已经提供了lock和同步等。但是在分布式情况下,往往存在多个进程对一些资源产生竞争...分布式锁顾明思议就是可以满足分布式情况下的并发锁。

    通过zookeeper实现分布式锁

    【Zookeeper实现分布式锁】 Zookeeper 是 Apache ...总之,Zookeeper 的分布式锁机制是基于其强大的一致性特性和事件通知能力实现的,它在分布式系统中扮演着至关重要的角色,帮助协调和管理分布式环境下的并发操作。

    redis和zookeeper实现分布式锁的区别

    **Zookeeper分布式锁** Zookeeper是一个高可用的分布式协调服务,它维护了一致的命名空间和分布式事件通知。Zookeeper中的分布式锁通常通过创建临时节点(ephemeral nodes)来实现。当客户端创建一个临时节点并持有...

    吊打面试官之基于zookeeper实现分布式锁源码

    本主题将深入探讨如何利用ZooKeeper实现分布式锁,并结合SpringCloud生态进行应用。ZooKeeper是一个分布式协调服务,而分布式锁是它的一个重要应用场景。 **ZooKeeper的特性与角色** 1. **强一致性**:ZooKeeper...

    Zookeeper实现分布式锁

    4. **zkLockTest**:这个文件很可能是实现Zookeeper分布式锁的测试代码,可能包含客户端的连接、锁的获取和释放、异常处理等逻辑。通过对这个测试代码的分析和运行,我们可以深入理解Zookeeper分布式锁的工作机制。 ...

    《Paxos到Zookeeper——分布式一致性原理与实践》高清完整版

    5. 实战应用:通过具体案例展示如何在实际项目中运用Zookeeper解决分布式协调问题,例如配置管理、服务发现、分布式锁等。 6. 高可用与故障恢复:探讨Zookeeper的容错机制,如何保证服务的高可用性和数据的一致性。 ...

    zookeeper分布式锁实例源码

    在这个场景下,我们将关注ZooKeeper如何实现分布式锁,特别是不可重入锁、可重入锁以及可重入读写锁的概念与实践。 首先,我们要理解什么是分布式锁。在多节点并发访问共享资源时,分布式锁能确保同一时刻只有一个...

    基于Zookeeper实现分布式锁实践教程

    通过这种方式,多个节点可以在Zookeeper的帮助下,安全地实现分布式锁,确保资源的互斥访问。 总的来说,Zookeeper作为分布式协调服务,其强大的数据模型和API为实现诸如分布式锁这样的功能提供了坚实的基础。通过...

    浅谈Java(SpringBoot)基于zookeeper的分布式锁实现

    Java(SpringBoot)基于zookeeper的分布式锁实现 本文主要介绍了Java(SpringBoot)基于zookeeper的分布式锁实现,通过示例代码详细介绍了分布式锁的实现过程,对大家的学习或者工作具有一定的参考学习价值。 分布式锁...

    zookeeper分布式锁实现和客户端简单实现

    Zookeeper提供了一种类似于文件系统的数据模型,可以用于命名服务、配置管理、集群管理、分布式锁等场景。它具有强一致性、高可用性和高性能的特点,是实现分布式锁的理想选择。 **Zookeeper的分布式锁实现原理** ...

    zookeeper的分布式全局锁纯代码解决方案

    在这个"zookeeper的分布式全局锁纯代码解决方案"中,我们将探讨如何利用Zookeeper来构建一套易于理解和扩展的分布式锁。 首先,Zookeeper的特性使其成为实现分布式锁的理想选择。Zookeeper提供了原子性的读写操作、...

    Zookeeper 分布式重入排它锁实现

    Zookeeper提供了基于其强大的数据一致性特性的分布式锁实现,其中包括了重入排他锁。 **一、Zookeeper的分布式锁原理** 1. **节点创建与删除**:在Zookeeper中,锁的实现通常依赖于临时节点(ephemeral nodes)。...

Global site tag (gtag.js) - Google Analytics