码迷,mamicode.com
首页 > 其他好文 > 详细

zookeeper 实现分布式锁(cpu占用低)

时间:2020-07-07 17:48:36      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:nsa   eve   override   顺序   http   分布   llb   unsafe   sorted   

原理:

1 zookeeper 可以建立临时节点文件 znode  结构如高度为2的树  在 basepath+lockname上建立  basepath+lockname---1 basepath+lockname---2 basepath+lockname---3 的顺序节点

2 watcher机制。可以建立某一个节点的watcher callback method A,当be watch的node change, 会call the A mehod

note: these code not 原创,摘自 https://dzone.com/articles/distributed-lock-using

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

public class DistributedLock {
    private final ZooKeeper zk;
    private final String lockBasePath;
    private final String lockName;
    private String lockPath;
    public DistributedLock(ZooKeeper zk, String lockBasePath, String lockName) {
        this.zk = zk;
        this.lockBasePath = lockBasePath;
        this.lockName = lockName;
    }
    public void lock() throws IOException {
        try {
// lockPath will be different than (lockBasePath + "/" + lockName) becuase of the sequence number ZooKeeper appends
            lockPath = zk.create(lockBasePath + "/" + lockName, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
            final Object lock = new Object();
            synchronized(lock) {
                while(true) {
                    List<String> nodes = zk.getChildren(lockBasePath, new Watcher() {
                        @Override
                        public void process(WatchedEvent event) {
                            synchronized (lock) {
                                lock.notifyAll();
                            }
                        }
                    });
                    Collections.sort(nodes); // ZooKeeper node names can be sorted lexographically
                    if (lockPath.endsWith(nodes.get(0))){
                        return;
                    } else {
                        lock.wait();
                    }
                }
            }
        } catch (KeeperException e) {
            throw new IOException (e);
        } catch (InterruptedException e) {
            throw new IOException (e);
        }
    }
    public void unlock() throws IOException {
        try {
            zk.delete(lockPath, -1);
            lockPath = null;
        } catch (KeeperException e) {
            throw new IOException (e);
        } catch (InterruptedException e) {
            throw new IOException (e);
        }
    }
}

 

zookeeper 实现分布式锁(cpu占用低)

标签:nsa   eve   override   顺序   http   分布   llb   unsafe   sorted   

原文地址:https://www.cnblogs.com/tecnologycc/p/13261851.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!