ZK简单的实现分布式锁

ZK实现分布式锁的原理

在这里插入图片描述


```java
package com.example.springbatchdemo.zookeeper;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.exception.ZkNodeExistsException;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;


public class ZKDistributedLock implements Lock {
    // 锁路径(临时顺序节点们的父路径)
    private String lockPath;
    // zk客户端
    private ZkClient client;
    // 这里为了方便,用ThreadLocal实现的线程安全,也可以用其他方式
    // 当前节点的路径
    private ThreadLocal<String> currentPath = new ThreadLocal<>();
    // 前一个节点的路径
    private ThreadLocal<String> beforePath = new ThreadLocal<>();
    // 锁重入计数
    private ThreadLocal<Integer> reentrantCount = new ThreadLocal<>();


    public ZKDistributedLock(String lockPath) {
        super();
        this.lockPath = lockPath;
        client = new ZkClient("47.112.110.71:2181");
        client.setZkSerializer(new MyZkSerializer());
        if (!this.client.exists(lockPath)) {
            try {
                this.client.createPersistent(lockPath);
            } catch (ZkNodeExistsException e) {
                // 无需处理,已存在就直接用即可
            }
        }
    }

    @Override
    public boolean tryLock() {
        if (this.reentrantCount.get() != null) {
            int count = this.reentrantCount.get();
            if (count > 0) {
                this.reentrantCount.set(++count);
                return true;
            }
        }

        if (this.currentPath.get() == null) {
            // 创建临时顺序节点,zk中创建节点必须赋值,所以这里随便赋值aaa
            currentPath.set(this.client.createEphemeralSequential(lockPath + "/", "aaa"));
        }
        // 获得所有的子
        List<String> children = this.client.getChildren(lockPath);

        // 排序list
        Collections.sort(children);

        // 判断当前节点是否是最小的
        if (currentPath.get().equals(lockPath + "/" + children.get(0))) {
            this.reentrantCount.set(1);
            return true;
        } else {
            // 取到前一个
            // 得到字节的索引号
            int curIndex = children.indexOf(currentPath.get().substring(lockPath.length() + 1));
            beforePath.set(lockPath + "/" + children.get(curIndex - 1));
        }
        return false;
    }

    @Override
    public void lock() {
        if (!tryLock()) {
            // 阻塞等待
            waitForLock();
            // 再次尝试加锁
            lock();
        }
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {

        // 重入的释放锁处理
        if (this.reentrantCount.get() != null) {
            int count = this.reentrantCount.get();
            if (count > 1) {
                this.reentrantCount.set(--count);
                return;
            } else {
                this.reentrantCount.set(null);
            }
        }
        // 删除当前节点
        this.client.delete(this.currentPath.get());
    }

    @Override
    public Condition newCondition() {
        return null;
    }

    private void waitForLock() {
        CountDownLatch cdl = new CountDownLatch(1);

        // 注册watcher
        IZkDataListener listener = new IZkDataListener() {

            @Override
            public void handleDataDeleted(String dataPath) throws Exception {
                System.out.println("-----监听到节点被删除----");
                cdl.countDown();
            }

            @Override
            public void handleDataChange(String dataPath, Object data) throws Exception {

            }
        };
        client.subscribeDataChanges(this.beforePath.get(), listener);

        if (this.client.exists(this.beforePath.get())) {
            try {
                // 阻塞
                cdl.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 醒来后,取消watcher
        client.unsubscribeDataChanges(this.beforePath.get(), listener);
    }

    public static void main(String[] args) {
        // 并发数
        int currency = 50;

        // 利用CyclicBarrier模拟并发场景,CyclicBarrier的作用是集满指定线程个数,一起发出去
        CyclicBarrier cb = new CyclicBarrier(currency);

        for (int i = 0; i < currency; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "---------Ready---------------");
                // 等待一起出发
                try {
                    cb.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
                ZKDistributedLock lock = new ZKDistributedLock("/distLock");

                try {
                    lock.lock();
                    System.out.println(Thread.currentThread().getName() + " 获得锁!");
                } finally {
                    lock.unlock();
                }
            }).start();

        }

    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值