这篇文章给大家分享的是有关zookeeper如何实现竞争锁的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
package com.hgs.sharelocks;import java.util.Collections;import java.util.List;import org.apache.zookeeper.CreateMode;import org.apache.zookeeper.WatchedEvent;import org.apache.zookeeper.Watcher;import org.apache.zookeeper.Watcher.Event.EventType;import org.apache.zookeeper.ZooDefs.Ids;import org.apache.zookeeper.ZooKeeper;public class ZKsharelocks {private ZooKeeper zk = null; private final static String connectString = "192.168.6.131:2181,192.168.6.132:2181,192.168.6.133:2181"; private final static int sessionTimeout = 2000; private final static String parentNode="/servers"; private final static String subNode="/sub"; private volatile String myPath = null; private boolean lockflag = false;public static void main(String[] args) throws Exception {ZKsharelocks sl = new ZKsharelocks();sl.getConnect();Thread.sleep(Long.MAX_VALUE);}public void getConnect() throws Exception{//创建实例zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {@Overridepublic void process(WatchedEvent event) {//判断事件的类型以及路径是否是业务路径if(event.getType()==EventType.NodeChildrenChanged&&event.getPath().equals(parentNode)) {List<String> inchild = null; try { //得到子节点,继续监听 inchild = zk.getChildren(parentNode, true); //排序 Collections.sort(inchild); //判断返回的时间路径不是null并且最小的子路经是当天路径 if(myPath != null&&inchild.size()>0&&inchild.indexOf(myPath.substring(parentNode.length()+1))==0) { doSomthing(); Thread.sleep(2000); myPath=zk.create(parentNode+subNode, null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); }} catch (Exception e) {e.printStackTrace();}}}});//首先创建一个临时的序列的条目myPath=zk.create(parentNode+subNode, null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);//得到父节点下面的子目录数并进行监听List<String> childs = zk.getChildren(parentNode, true);//判断进入到的时候是否只有自己,如果只有自己则可以做业务逻辑if(childs.size()==1) {//业务方法,在业务方法内有删除myPath条目的操作doSomthing();//删除完成后继续myPath=zk.create(parentNode+subNode, null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);}}public void doSomthing() throws Exception {System.out.println("get the lock..."+Thread.currentThread().getName());//得到锁完成业务后,删除持有的锁,即删除该条目zk.delete(myPath, -1);}}
感谢各位的阅读!关于“zookeeper如何实现竞争锁”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!