zookeeper分布式锁之InterProcessMutex

zookeeper分布式锁之InterProcessMutex

zookeeper分布式锁原理

•核心思想:当客户端要获取锁,则创建节点,使用完锁,则删除该节点。

1.客户端获取锁时,在lock节点下创建临时顺序节点。

2.然后获取lock下面的所有子节点,客户端获取到所有的子节点之后,如果发现自己创建的子节点序号最小,那么就认为该客户端获取到了锁。使用完锁后,将该节点删除。

3.如果发现自己创建的节点并非lock所有子节点中最小的,说明自己还没有获取到锁,此时客户端需要找到比自己小的那个节点,同时对其注册事件监听器,监听删除事件。

4.如果发现比自己小的那个节点被删除,则客户端的 Watcher会收到相应通知,此时再次判断自己创建的节点 是否是lock子节点中序号最小的,如果是则获取到了锁,如果不是则重复以上步骤继续获取到比自己小的一个节点并注册监听。

InterProcessMutex:分布式可重入排它锁

  1. 首先根据当前线程去查看是否存在锁数据,且如果此时这个线程正在使用这个锁,则改变锁的状态次数+1,并直接返回true。
  2. 没有获取到所数据则进入else
    1. 先去创建锁数据
    2. 然后排队等待获取锁
  3. 获取到返回true,否则false
//外部获取锁接口

public boolean acquire(long time, TimeUnit unit) throws Exception {
        return this.internalLock(time, unit);
    }
    

//获取锁逻辑
private boolean internalLock(long time, TimeUnit unit) throws Exception {
    //当前线程
        Thread currentThread = Thread.currentThread();
    //1.从lock节点中获取锁节点数据
        InterProcessMutex.LockData lockData = (InterProcessMutex.LockData)this.threadData.get(currentThread);
        if (lockData != null) {
            lockData.lockCount.incrementAndGet();
            return true;
        } else {
            //在一定时间内创建锁并获取锁
            String lockPath = this.internals.attemptLock(time, unit, this.getLockNodeBytes());
            if (lockPath != null) {
                InterProcessMutex.LockData newLockData = new InterProcessMutex.LockData(currentThread, lockPath);
                this.threadData.put(currentThread, newLockData);
                return true;
            } else {
                return false;
            }
        }
    }
    
  //在一定时间内创建锁并获取锁
String attemptLock(long time, TimeUnit unit, byte[] lockNodeBytes) throws Exception {
        long startMillis = System.currentTimeMillis();
        Long millisToWait = unit != null ? unit.toMillis(time) : null;
        byte[] localLockNodeBytes = this.revocable.get() != null ? new byte[0] : lockNodeBytes;
        int retryCount = 0;
        String ourPath = null;
        boolean hasTheLock = false;
        boolean isDone = false;

        while(!isDone) {
            isDone = true;

            try {
                //创建锁
                ourPath = this.driver.createsTheLock(this.client, this.path, localLockNodeBytes);
                //在一定时间获取锁,获取到返回true,失败咋返回false
                hasTheLock = this.internalLockLoop(startMillis, millisToWait, ourPath);
            } catch (NoNodeException var14) {
                if (!this.client.getZookeeperClient().getRetryPolicy().allowRetry(retryCount++, System.currentTimeMillis() - startMillis, RetryLoop.getDefaultRetrySleeper())) {
                    throw var14;
                }

                isDone = false;
            }
        }

        return hasTheLock ? ourPath : null;
    }

InterProcessMutex实现模拟12306

1,创建线程进行加锁设置

public class Ticket12306 implements Runnable{
    private int tickets = 10;//数据库的票数
    //分布式可重入排它锁
    private InterProcessMutex lock ;
    @Override
    public void run() {
        while(true){
            //获取锁
            try {
            lock.acquire(3, TimeUnit.SECONDS);
                if(tickets > 0){
                    System.out.println(Thread.currentThread()+":"+tickets);
                    Thread.sleep(100);
                    tickets--;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                //释放锁
                try {
                    lock.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }
}

2,创建连接,并且初始化锁

public Ticket12306(){
    //重试策略
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000, 10);
    //2.第二种方式
    //CuratorFrameworkFactory.builder();
    CuratorFramework client = CuratorFrameworkFactory.builder()
        .connectString("192.168.149.135:2181")
        .sessionTimeoutMs(60 * 1000)
        .connectionTimeoutMs(15 * 1000)
        .retryPolicy(retryPolicy)
        .build();
    //开启连接
    client.start();
    lock = new InterProcessMutex(client,"/lock");
}

3,运行多个线程进行测试

public class LockTest {
    public static void main(String[] args) {
        Ticket12306 ticket12306 = new Ticket12306();
        //创建客户端
        Thread t1 = new Thread(ticket12306,"携程");
        Thread t2 = new Thread(ticket12306,"飞猪");
        t1.start();
        t2.start();
    }
}

t1 = new Thread(ticket12306,“携程”);
Thread t2 = new Thread(ticket12306,“飞猪”);
t1.start();
t2.start();
}
}


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当面试中涉及到ZooKeeper分布式锁的问题,通常会涉及以下几个方面: 1. 什么是ZooKeeper分布式锁ZooKeeper分布式锁是基于ZooKeeper提供的原语实现的一种分布式锁机制。它利用了ZooKeeper的有序临时节点和Watcher机制来实现锁的竞争和释放。 2. ZooKeeper分布式锁的实现原理是什么? ZooKeeper分布式锁的实现原理主要依赖于ZooKeeper的有序临时节点和Watcher机制。当一个线程需要获取锁时,它会在ZooKeeper的指定路径上创建一个有序临时节点,并且注册一个Watcher来监听前一个节点是否存在。如果前一个节点不存在,则该线程获取锁成功;否则,该线程需要等待前一个节点被删除后继续竞争锁。 3. ZooKeeper分布式锁存在的问题有哪些? ZooKeeper分布式锁虽然实现了基本的锁机制,但仍然存在以下问题: - 网络延迟:由于网络延迟等原因,可能导致锁的竞争时间增加,影响系统的性能。 - 节点故障:如果持有锁的节点发生故障,可能导致其他节点无法获取锁或长时间等待。 - 死锁:如果在获取锁的过程中发生故障或异常,可能导致死锁情况的发生。 4. 如何解决ZooKeeper分布式锁的问题? 为了解决ZooKeeper分布式锁存在的问题,可以采取以下策略: - 设置合理的超时时间,避免长时间等待导致系统性能下降。 - 使用心跳机制来检测节点的存活状态,及时处理节点故障。 - 采用分布式协调框架或工具,如Curator、Spring Integration等,简化分布式锁的使用和管理。 这些是一些常见的ZooKeeper分布式锁面试题及其答案,希望能对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值