zookeeper分布式锁

zookeeper分布式锁,第1张

zookeeper分布式
package com.hikvision.mes.service.system.service.util;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class WatchCallBack  implements Watcher,AsyncCallback.StringCallback,AsyncCallback.Children2Callback,AsyncCallback.StatCallback{
    ZooKeeper zk ;

    String threadName;

    String pathName;

    CountDownLatch cc = new CountDownLatch(1);

    public String getPathName() {
        return pathName;
    }

    public void setPathName(String pathName) {
        this.pathName = pathName;
    }

    public String getThreadName() {
        return threadName;
    }

    public void setThreadName(String threadName) {
        this.threadName = threadName;
    }

    public ZooKeeper getZk() {
        return zk;
    }

    public void setZk(ZooKeeper zk) {
        this.zk = zk;
    }

    public void tryLock(){
        try {
            System.out.println("threadName=="+threadName);
            zk.create("/zookeeper",threadName.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL,  this,"abc");
            cc.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void unLock(){
        try {
            zk.delete(pathName,-1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void process(WatchedEvent event) {
        switch (event.getType()) {
            case None:
                break;
            case NodeCreated:
                break;
            case NodeDeleted:
                zk.getChildren("/",false,  this,"sdf");
                break;
            case NodeDataChanged:
                break;
            case NodeChildrenChanged:
                break;
        }
    }


    @Override
    public void processResult(int rc, String path, Object ctx, String name) {
        if(name != null){
            System.out.println("pathName=="+name);
            pathName = name;
            zk.getChildren("/",false,this,"sdf");
        }

    }

    @Override
    public void processResult(int rc, String path, Object ctx, List children, Stat stat) {
        //排序一下然后获取第一个注册的节点
        Collections.sort(children);
        int i = children.indexOf(pathName.substring(1));
        if( i==0 ){
            cc.countDown();
        }else {
           zk.exists("/"+children.get(i-1),this, this,"sdf");
        }
    }

    @Override
    public void processResult(int rc, String path, Object ctx, Stat stat) {

    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5068388.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-16
下一篇 2022-11-16

发表评论

登录后才能评论

评论列表(0条)

保存