欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

zookeeper【5】分布式锁

程序员文章站 2023-03-31 19:37:40
我们常说的锁是单进程多线程锁,在多线程并发编程中,用于线程之间的数据同步,保护共享资源的访问。而分布式锁,指在分布式环境下,保护跨进程、跨主机、跨网络的共享资源,实现互斥访问,保证一致性。 架构图: 分布式锁获取思路a、在获取分布式锁的时候在locker节点下创建临时顺序节点,释放锁的时候删除该临时 ......

我们常说的锁是单进程多线程锁,在多线程并发编程中,用于线程之间的数据同步,保护共享资源的访问。而分布式锁,指在分布式环境下,保护跨进程、跨主机、跨网络的共享资源,实现互斥访问,保证一致性。

 

架构图:

zookeeper【5】分布式锁

 

分布式锁获取思路
a、在获取分布式锁的时候在locker节点下创建临时顺序节点,释放锁的时候删除该临时节点。

b、客户端调用createnode方法在locker下创建临时顺序节点,然后调用getchildren(“locker”)来获取locker下面的所有子节点,注意此时不用设置任何watcher。

c、客户端获取到所有的子节点path之后,如果发现自己创建的子节点序号最小,那么就认为该客户端获取到了锁。

d、如果发现自己创建的节点并非locker所有子节点中最小的,说明自己还没有获取到锁,此时客户端需要找到比自己小的那个节点,然后对其调用exist()方法,同时对其注册事件监听器。

e、之后,让这个被关注的节点删除,则客户端的watcher会收到相应通知,此时再次判断自己创建的节点是否是locker子节点中序号最小的,如果是则获取到了锁,如果不是则重复以上步骤继续获取到比自己小的一个节点并注册监听。

 

实现代码:

import org.i0itec.zkclient.izkdatalistener;
import org.i0itec.zkclient.zkclient;
import org.i0itec.zkclient.exception.zknonodeexception;

import java.util.collections;
import java.util.comparator;
import java.util.list;
import java.util.concurrent.countdownlatch;
import java.util.concurrent.timeunit;

public class basedistributedlock {

    private final zkclientext client;
    private final string  path;
    private final string  basepath;
    private final string  lockname;
    private static final integer  max_retry_count = 10;

    public basedistributedlock(zkclientext client, string path, string lockname){

        this.client = client;
        this.basepath = path;
        this.path = path.concat("/").concat(lockname);
        this.lockname = lockname;

    }

    // 删除成功获取锁之后所创建的那个顺序节点
    private void deleteourpath(string ourpath) throws exception{
        client.delete(ourpath);
    }

    // 创建临时顺序节点
    private string createlocknode(zkclient client, string path) throws exception{
        return client.createephemeralsequential(path, null);
    }

    // 等待比自己次小的顺序节点的删除
    private boolean waittolock(long startmillis, long millistowait, string ourpath) throws exception{

        boolean  havethelock = false;
        boolean  dodelete = false;

        try {

            while ( !havethelock ) {
                // 获取/locker下的经过排序的子节点列表
                list<string> children = getsortedchildren();

                // 获取刚才自己创建的那个顺序节点名
                string sequencenodename = ourpath.substring(basepath.length()+1);

                // 判断自己排第几个
                int  ourindex = children.indexof(sequencenodename);
                if (ourindex < 0){ // 网络抖动,获取到的子节点列表里可能已经没有自己了
                    throw new zknonodeexception("节点没有找到: " + sequencenodename);
                }

                // 如果是第一个,代表自己已经获得了锁
                boolean isgetthelock = ourindex == 0;

                // 如果自己没有获得锁,则要watch比我们次小的那个节点
                string  pathtowatch = isgetthelock ? null : children.get(ourindex - 1);

                if ( isgetthelock ){
                    havethelock = true;

                } else {

                    // 订阅比自己次小顺序节点的删除事件
                    string  previoussequencepath = basepath .concat( "/" ) .concat( pathtowatch );
                    final countdownlatch latch = new countdownlatch(1);
                    final izkdatalistener previouslistener = new izkdatalistener() {

                        public void handledatadeleted(string datapath) throws exception {
                            latch.countdown(); // 删除后结束latch上的await
                        }

                        public void handledatachange(string datapath, object data) throws exception {
                            // ignore
                        }
                    };

                    try {
                        //订阅次小顺序节点的删除事件,如果节点不存在会出现异常
                        client.subscribedatachanges(previoussequencepath, previouslistener);

                        if ( millistowait != null ) {
                            millistowait -= (system.currenttimemillis() - startmillis);
                            startmillis = system.currenttimemillis();
                            if ( millistowait <= 0 ) {
                                dodelete = true;    // timed out - delete our node
                                break;
                            }

                            latch.await(millistowait, timeunit.microseconds); // 在latch上await
                        } else {
                            latch.await(); // 在latch上await
                        }

                        // 结束latch上的等待后,继续while重新来过判断自己是否第一个顺序节点
                    }
                    catch ( zknonodeexception e ) {
                        //ignore
                    } finally {
                        client.unsubscribedatachanges(previoussequencepath, previouslistener);
                    }

                }
            }
        }
        catch ( exception e ) {
            //发生异常需要删除节点
            dodelete = true;
            throw e;
        } finally {
            //如果需要删除节点
            if ( dodelete ) {
                deleteourpath(ourpath);
            }
        }
        return havethelock;
    }

    private string getlocknodenumber(string str, string lockname) {
        int index = str.lastindexof(lockname);
        if ( index >= 0 ) {
            index += lockname.length();
            return index <= str.length() ? str.substring(index) : "";
        }
        return str;
    }

    // 获取/locker下的经过排序的子节点列表
    list<string> getsortedchildren() throws exception {
        try{

            list<string> children = client.getchildren(basepath);
            collections.sort(
                    children, new comparator<string>() {
                        public int compare(string lhs, string rhs) {
                            return getlocknodenumber(lhs, lockname).compareto(getlocknodenumber(rhs, lockname));
                        }
                    }
            );
            return children;

        } catch (zknonodeexception e){
            client.createpersistent(basepath, true);
            return getsortedchildren();
        }
    }

    protected void releaselock(string lockpath) throws exception{
        deleteourpath(lockpath);
    }

    protected string attemptlock(long time, timeunit unit) throws exception {

        final long      startmillis = system.currenttimemillis();
        final long      millistowait = (unit != null) ? unit.tomillis(time) : null;

        string          ourpath = null;
        boolean         hasthelock = false;
        boolean         isdone = false;
        int             retrycount = 0;

        //网络闪断需要重试一试
        while ( !isdone ) {
            isdone = true;

            try {
                // 在/locker下创建临时的顺序节点
                ourpath = createlocknode(client, path);
                // 判断自己是否获得了锁,如果没有获得那么等待直到获得锁或者超时
                hasthelock = waittolock(startmillis, millistowait, ourpath);
            } catch ( zknonodeexception e ) { // 捕获这个异常
                if ( retrycount++ < max_retry_count ) { // 重试指定次数
                    isdone = false;
                } else {
                    throw e;
                }
            }
        }
        if ( hasthelock ) {
            return ourpath;
        }

        return null;
    }


}
import java.util.concurrent.timeunit;

public interface distributedlock {

    /*
     * 获取锁,如果没有得到就等待
     */
    public void acquire() throws exception;

    /*
     * 获取锁,直到超时
     */
    public boolean acquire(long time, timeunit unit) throws exception;

    /*
     * 释放锁
     */
    public void release() throws exception;


}
import java.io.ioexception;
import java.util.concurrent.timeunit;

public class simpledistributedlockmutex extends basedistributedlock implements
        distributedlock {

    //锁名称前缀,成功创建的顺序节点如lock-0000000000,lock-0000000001,...
    private static final string lock_name = "lock-";

    // zookeeper中locker节点的路径
    private final string basepath;

    // 获取锁以后自己创建的那个顺序节点的路径
    private string ourlockpath;

    private boolean internallock(long time, timeunit unit) throws exception {

        ourlockpath = attemptlock(time, unit);
        return ourlockpath != null;

    }

    public simpledistributedlockmutex(zkclientext client, string basepath){

        super(client,basepath,lock_name);
        this.basepath = basepath;

    }

    // 获取锁
    public void acquire() throws exception {
        if ( !internallock(-1, null) ) {
            throw new ioexception("连接丢失!在路径:'"+basepath+"'下不能获取锁!");
        }
    }

    // 获取锁,可以超时
    public boolean acquire(long time, timeunit unit) throws exception {

        return internallock(time, unit);
    }

    // 释放锁
    public void release() throws exception {

        releaselock(ourlockpath);
    }


}
import org.i0itec.zkclient.serialize.bytespushthroughserializer;

public class testdistributedlock {

    public static void main(string[] args) {

        final zkclientext zkclientext1 = new zkclientext("192.168.1.105:2181", 5000, 5000, new bytespushthroughserializer());
        final simpledistributedlockmutex mutex1 = new simpledistributedlockmutex(zkclientext1, "/mutex");

        final zkclientext zkclientext2 = new zkclientext("192.168.1.105:2181", 5000, 5000, new bytespushthroughserializer());
        final simpledistributedlockmutex mutex2 = new simpledistributedlockmutex(zkclientext2, "/mutex");

        try {
            mutex1.acquire();
            system.out.println("client1 locked");
            thread client2thd = new thread(new runnable() {

                public void run() {
                    try {
                        mutex2.acquire();
                        system.out.println("client2 locked");
                        mutex2.release();
                        system.out.println("client2 released lock");

                    } catch (exception e) {
                        e.printstacktrace();
                    }
                }
            });
            client2thd.start();
            thread.sleep(5000);
            mutex1.release();
            system.out.println("client1 released lock");

            client2thd.join();

        } catch (exception e) {

            e.printstacktrace();
        }

    }

}
import org.i0itec.zkclient.zkclient;
import org.i0itec.zkclient.serialize.zkserializer;
import org.apache.zookeeper.data.stat;

import java.util.concurrent.callable;

public class zkclientext extends zkclient {

    public zkclientext(string zkservers, int sessiontimeout, int connectiontimeout, zkserializer zkserializer) {
        super(zkservers, sessiontimeout, connectiontimeout, zkserializer);
    }

    @override
    public void watchfordata(final string path) {
        retryuntilconnected(new callable<object>() {

            public object call() throws exception {
                stat stat = new stat();
                _connection.readdata(path, stat, true);
                return null;
            }

        });
    }

}