ZK实现分布式可重入锁(二)

原理:
利用临时顺序节点来实现分布式可重入锁

锁实现——ZKLock2

package com.test.tomcat.common;

import lombok.Data;
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.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @program: test
 * @description:利用临时顺序节点来实现分布式锁
 * 获取锁:取排队号(创建自己的临时顺序节点),然后判断自己是否是最小号,如是,则获得锁;不是,则注册前一节点的watcher,阻塞等待
 * 释放锁:删除自己创建的临时顺序节点
 * @author: peng.gao
 * @create: 2019-07-10 19:30
 **/
@Data
public class ZKLock2 implements Lock {

    private String lockPath;
    private ZkClient client;
    /**
     * 当前节点
     */
    private ThreadLocal<String> currentPath = new ThreadLocal<>();
    /**
     * 上一
     */
    private ThreadLocal<String> beforePath = new ThreadLocal<>();

    /**
     * 重入计数
     */
    private ThreadLocal<Integer> reentrantCount = new ThreadLocal<>();

    public ZKLock2(String lockPath) {
        this.lockPath = lockPath;
        this.client = new ZkClient("localhost:2181");
        client.setZkSerializer(new MyZkSerializer());
        if (!this.client.exists(lockPath)) {
            try {
                //创建普通节点
                client.createPersistent(lockPath);
            } catch (ZkNodeExistsException e) {

            }
        }
    }

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

    private void waitForLock() {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        //watcher
        IZkDataListener listener = new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object o) throws Exception {
            }

            @Override
            public void handleDataDeleted(String s) throws Exception {
                System.out.println("-----监听到节点被删除");
                countDownLatch.countDown();
            }
        };
        //给前一个节点注册监听器
        client.subscribeDataChanges(this.beforePath.get(), listener);
        if (this.client.exists(beforePath.get())) {
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 节点删除后,取消watcher
        client.unsubscribeDataChanges(this.beforePath.get(), listener);

    }


    @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) {
            //创建临时顺序节点
            currentPath.set(this.client.createEphemeralSequential(lockPath + "/", "aaa"));
        }
        //获取所有的子节点
        List<String> children = this.client.getChildren(lockPath);
        //排序
        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 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(currentPath.get());
    }


    public static void main(String[] args) throws InterruptedException {
        int count = 50;
        //循环屏障
        CyclicBarrier cb = new CyclicBarrier(count);
        for (int i = 0; i < count; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "-------我准备好-------");
                    //等待一起执行
                    try {
                        cb.await();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    ZKLock2 lock = new ZKLock2("/zkLock22");
                    try {
                        lock.lock();
                        System.out.println(Thread.currentThread().getName() + "-------获得了锁-------");
                    } finally {
                        lock.unlock();
                    }

                }
            }).start();
        }
    }

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


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

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }
}

ZK序列化实现——MyZkSerializer

package com.test.tomcat.common;

import org.I0Itec.zkclient.exception.ZkMarshallingError;
import org.I0Itec.zkclient.serialize.ZkSerializer;

import java.io.UnsupportedEncodingException;

/**
 * @program: test
 * @description:
 * @author: peng.gao
 * @create: 2019-07-10 00:05
 **/
public class MyZkSerializer implements ZkSerializer {
    private static final String charset = "utf-8";

    @Override
    public byte[] serialize(Object o) throws ZkMarshallingError {
        try {
            return String.valueOf(o).getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new ZkMarshallingError(e);
        }
    }

    @Override
    public Object deserialize(byte[] bytes) throws ZkMarshallingError {

        try {
            return new String(bytes,charset);
        } catch (UnsupportedEncodingException e) {
            throw new ZkMarshallingError(e);
        }
    }
}

下面是一个基于 ZooKeeper 实现分布式锁的 Java 代码示例: ```java import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.Stat; public class DistributedLock { private static final String LOCK_ROOT_PATH = "/locks"; private static final String LOCK_NODE_PREFIX = "lock-"; private final String lockPath; private final ZooKeeper zk; private String lockNode; private CountDownLatch lockAcquiredSignal; public DistributedLock(String zookeeperUrl, String lockPath) throws Exception { this.lockPath = LOCK_ROOT_PATH + "/" + lockPath; this.zk = new ZooKeeper(zookeeperUrl, 3000, null); ensureLockPathExists(); } public void lock() throws Exception { while (true) { try { lockNode = zk.create(lockPath + "/" + LOCK_NODE_PREFIX, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); lockAcquiredSignal = new CountDownLatch(1); waitForLock(); return; } catch (KeeperException.NodeExistsException e) { // node already exists, wait for the previous holder to release the lock waitForPreviousLock(); } } } public void unlock() throws Exception { zk.delete(lockNode, -1); lockNode = null; lockAcquiredSignal.countDown(); } private void ensureLockPathExists() throws Exception { if (zk.exists(lockPath, false) == null) { zk.create(lockPath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } } private void waitForPreviousLock() throws Exception { List<String> lockNodes = zk.getChildren(lockPath, false); Collections.sort(lockNodes); int currentLockIndex = lockNodes.indexOf(lockNode.substring(lockPath.length() + 1)); if (currentLockIndex <= 0) { throw new IllegalStateException("Lock node not found: " + lockNode); } String previousLockNode = lockPath + "/" + lockNodes.get(currentLockIndex - 1); Stat previousLockStat = zk.exists(previousLockNode, new LockWatcher()); if (previousLockStat != null) { lockAcquiredSignal.await(); } } private void waitForLock() throws Exception { List<String> lockNodes = zk.getChildren(lockPath, false); Collections.sort(lockNodes); int currentLockIndex = lockNodes.indexOf(lockNode.substring(lockPath.length() + 1)); if (currentLockIndex == 0) { // this is the first lock node, lock acquired return; } String previousLockNode = lockPath + "/" + lockNodes.get(currentLockIndex - 1); Stat previousLockStat = zk.exists(previousLockNode, new LockWatcher()); if (previousLockStat == null) { // previous lock node has been deleted, lock acquired return; } lockAcquiredSignal.await(); } private class LockWatcher implements Watcher { @Override public void process(WatchedEvent event) { if (event.getType() == Event.EventType.NodeDeleted) { lockAcquiredSignal.countDown(); } } } } ``` 使用示例: ```java DistributedLock lock = new DistributedLock("localhost:2181", "my-lock"); lock.lock(); try { // critical section } finally { lock.unlock(); } ``` 该示例代码使用了 ZooKeeper 的临时顺序节点来实现分布式锁。当多个节点同时请求时,它们会在 ZooKeeper 中创建一个临时顺序节点,并按照节点名称的顺序等待前面的节点释放。当被释放时,它会通知等待的节点,让它们尝试重新获得
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值