2024年最全Zookeeper:实现“分布式锁”的 Demo_zookeeper实现分布式锁demo,2024年最新实战讲述大数据跨平台框架应用

img
img

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

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 readChildren(String path, Watcher watcher) throws InterruptedException, KeeperException {
List 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执行完毕
线程-Thread-1执行完毕
线程-Thread-2执行完毕
end …


通过 ZkLock 打印的信息可以看出,已经成功模拟实现分布式锁








![img](https://img-blog.csdnimg.cn/img_convert/3b683223131b92bc7d05db332f897a2b.png)
![img](https://img-blog.csdnimg.cn/img_convert/892a70adb19eed82a7ec6a0c2e49b28d.png)

**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**

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


**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**

,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**

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


**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值