Zookeeper:实现“分布式锁”的 Demo_zookeeper实现分布式锁demo

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.Stat;

public class ActiveKeyValueStore extends ConnectionWatcher {

    private static final Charset CHARSET = StandardCharsets.UTF\_8;

    int state = 0;

    /\*\*
 \* 写入节点数据
 \*
 \* @param path 节点地址
 \* @param value 数据值
 \* @throws InterruptedException 中断异常
 \* @throws KeeperException ZooKeeper异常
 \*/
    public void write(String path, String value) throws InterruptedException, KeeperException {
        Stat stat = zk.exists(path, false);
        if (stat == null) {
            if (value == null) {
                zk.create(path, null,
                        ZooDefs.Ids.OPEN\_ACL\_UNSAFE, CreateMode.PERSISTENT);
            } else {
                zk.create(path, value.getBytes(CHARSET),
                        ZooDefs.Ids.OPEN\_ACL\_UNSAFE, CreateMode.PERSISTENT);
            }

        } else {
            if (value == null) {
                zk.setData(path, null, -1);
            } else {
                zk.setData(path, value.getBytes(CHARSET), -1);
            }

        }
    }
  
   public boolean lock(String path, String name) throws InterruptedException, KeeperException {
        boolean flag = tryLock(path, name);
        if (flag) {
            state++;
        }
        return flag;
    }

    public boolean tryLock(String path, String name) throws InterruptedException, KeeperException {

        String lockPath = path + "/" + name;
        zk.create(lockPath, null, ZooDefs.Ids.OPEN\_ACL\_UNSAFE, CreateMode.EPHEMERAL);

        List<String> waits = readChildren(path, null);
        Collections.sort(waits);
        if (waits.get(0).equals(name)) {
            return true;
        }
        CountDownLatch latch = new CountDownLatch(1);
        for (int i = 0; i < waits.size(); i++) {
            String cur = waits.get(i);
            if (!cur.equalsIgnoreCase(name)) {
                continue;
            }
            String prePath = path + "/" + waits.get(i - 1);
            zk.exists(prePath, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    latch.countDown();
                }
            });
            break;
        }
        latch.await();
        return true;
    }

    public boolean unlock(String path, String name) {
        if (state > 1) {
            state--;
            return true;
        }

        String lockPath = path + "/" + name;

        try {
            Stat stat = zk.exists(lockPath, false);
            int version = stat.getVersion();
            zk.delete(lockPath, version);
            state--;
            return true;
        } catch (Exception e) {
            System.out.println("unlock:" + lockPath + " ,exception,");
        }
        return false;
    }

    /\*\*
 \* 获取所有子节点
 \*
 \* @param path 节点地址
 \* @param watcher watcher
 \* @return 所有子节点
 \* @throws InterruptedException 中断异常
 \* @throws KeeperException ZooKeeper异常
 \*/
    public List<String> readChildren(String path, Watcher watcher) throws InterruptedException, KeeperException {
        List<String> childrens = null;
        if (watcher == null) {
            childrens = zk.getChildren(path, false);
        } else {
            childrens = zk.getChildren(path, watcher, null);
        }
        return childrens;
    }
}

4、ZkLock 类实现分布式锁
import lombok.SneakyThrows;
import org.apache.zookeeper.KeeperException;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class ZkLock {


    /\*\*
 \* 开启的线程数,模拟多客户端操作
 \*/
    private static final int CLIENTS\_NUM = 3;

    private final ActiveKeyValueStore store;

    public ZkLock(String hosts) throws IOException, InterruptedException {
        //定义一个类
        store = new ActiveKeyValueStore();
        //连接Zookeeper
        store.connect(hosts);
    }

    public static void testLock() {
        //线程计数器控制业务的执行
        final CountDownLatch countDownLatch = new CountDownLatch(CLIENTS\_NUM);
        for (int i = 0; i < CLIENTS\_NUM; i++) {
            new Thread() {
                @Override
                public void run() {

                }
            }.start();
        }
        try {
            // 堵塞线程,任务执行完后释放
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {

        String hosts = "localhost:2181";
        ZkLock zkLock = new ZkLock(hosts);

        // 创建父节点
        zkLock.store.write("/lock4", "父亲节点");
        //
        CountDownLatch latch = new CountDownLatch(CLIENTS\_NUM);
        for (int i = 0; i < CLIENTS\_NUM; i++) {

            int finalI = i;
            new Thread() {
                @SneakyThrows
                @Override
                public void run() {

                    String name = "Thread-" + String.valueOf(finalI);
                    zkLock.store.lock("/lock4", name);
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println("线程-" + name + "执行完毕");
                    latch.countDown();
                    zkLock.store.unlock("/lock4", name);


                }
            }.start();
        }
        latch.await();
        System.out.println("end ...");
    }


}


三、测试结果

ZkLock 代码测试结果如下:

线程-Thread-0执行完毕


![img](https://img-blog.csdnimg.cn/img_convert/875b7023d6016a4858c53d30bed565d3.png)
![img](https://img-blog.csdnimg.cn/img_convert/98f4ec27949d60426b8a2fcc77e9641f.png)
![img](https://img-blog.csdnimg.cn/img_convert/03dcbba70620c359ebd31d27f3f9ea33.png)

**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上大数据知识点,真正体系化!**

**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**

**[需要这份系统化资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618545628)**

SrS8LXHQ-1714426080109)]

**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上大数据知识点,真正体系化!**

**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**

**[需要这份系统化资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618545628)**

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值