一、分布式锁介绍
分布式锁主要用于在分布式环境中保护跨进程、跨主机、跨网络的共享资源实现互斥访问,以达到保证数据的一致性。
二、架构介绍

\"在这里插入图片描述\"

左边的整个区域表示一个Zookeeper集群,locker是Zookeeper的一个持久节点,node_1、node_2、node_3是locker这个持久节点下面的临时顺序节点。client_1、client_2、client_n表示多个客户端,Service表示需要互斥访问的共享资源。
三:思路
多个线程去zk下创建一个临时结点,如果一个线程创建结点成功,就代表获得锁了,如果创建失败,就进入等待状态,监听临时结点,直到释放锁,就是临时节点消失,再重新执行获取锁的操作。此种方式会有一个问题产生,就是如果在并发比较大的情况下,一个临时结点的消失,会造成很多线程同时会试图创建临时结点,这种方式会影响zk的稳定性,这个效应称为羊群效应。
代码实现

package com.cmcc.test;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class DistributedClient {  
    // 超时时间  
    private static final int SESSION_TIMEOUT = 50000;  
    // zookeeper server列表  
    private String hosts = \"192.168.100.10:2181\";  
    private String groupNode = \"locks\";  
    private String subNode = \"sub\";  

    private ZooKeeper zk;  
    // 当前client创建的子节点  
    private String thisPath;  
    // 当前client等待的子节点  
    private String waitPath;  
    private CountDownLatch latch = new CountDownLatch(1);  

    public Watcher getWatcher(final String msg) {
        return new Watcher() {
            public void process(WatchedEvent event) {
                try {
                    // 连接建立时, 打开latch, 唤醒wait在该latch上的线程
                    if (event.getState() == KeeperState.SyncConnected) {
                        latch.countDown();
                    }
                    // 发生了waitPath的删除事件
                    if (event.getType() == EventType.NodeDeleted && event.getPath().equals(waitPath)) {  
                        // 确认thisPath是否真的是列表中的最小节点  
                        List<String> childrenNodes = zk.getChildren(\"/\" + groupNode, false);  
                        String thisNode = thisPath.substring((\"/\" + groupNode + \"/\").length());  
                        // 排序  
                        Collections.sort(childrenNodes);  
                        int index = childrenNodes.indexOf(thisNode);  
                        if (index == 0) {  
                            // 确实是最小节点  
                            doSomething();  
                        } else {      // 否则说明waitPath是由于出现异常而挂掉的    // 更新waitPath  
                            waitPath = \"/\" + groupNode + \"/\" + childrenNodes.get(index - 1);  
                            // 重新注册监听, 并判断此时waitPath是否已删除  
                            if (zk.exists(waitPath, true) == null) {  
                                doSomething();  
                            }  
                        }  
                    }  
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }
    /** 
     * 连接zookeeper 
     */  
    public void connectZookeeper() throws Exception {  
        System.out.println(\"进入连接zookeeper函数中\");
        zk = new ZooKeeper(hosts, SESSION_TIMEOUT, new Watcher(){
            public void process(WatchedEvent event) {
                try {
                    // 连接建立时, 打开latch, 唤醒wait在该latch上的线程
                    if (event.getState() == KeeperState.SyncConnected) {
                        latch.countDown();
                    }
                    // 发生了waitPath的删除事件
                    if (event.getType() == EventType.NodeDeleted
                            && event.getPath().equals(waitPath)) {
                        System.out.println(\"进入waitpath路径的删除时间中了\");
                        doSomething();
                        System.out.println(\"执行节点被删除的通知时间:dosomething函数\");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        // 等待连接建立  
        latch.await();  

        // 创建子节点  
        thisPath = zk.create(\"/\" + groupNode + \"/\" + subNode, null, Ids.OPEN_ACL_UNSAFE,  
                CreateMode.EPHEMERAL_SEQUENTIAL);  
        System.out.println(\"thispath---\"+thisPath);
        // wait一小会, 让结果更清晰一些  
        Thread.sleep(10);  

        // 注意, 没有必要监听\"/locks\"的子节点的变化情况  
        List<String> childrenNodes = zk.getChildren(\"/\" + groupNode, false);  
        System.out.println(\"开始判断节点个数\");
        // 列表中只有一个子节点, 那肯定就是thisPath, 说明client获得锁  
        if (childrenNodes.size() == 1) {  
             System.out.println(\"孩子节点个数等于1\");
            doSomething();  
        } else {  
            System.out.println(\"孩子节点个数大于1\");
            String thisNode = thisPath.substring((\"/\" + groupNode + \"/\").length());  
            System.out.println(\"当前节点--\"+thisNode);
            // 排序  ------------后面才是重点的
            Collections.sort(childrenNodes);  
            int index = childrenNodes.indexOf(thisNode);  
            if (index == -1) {  
                // never happened  
            } else if (index == 0) {  
                // inddx == 0, 说明thisNode在列表中最小, 当前client获得锁  
                doSomething();  
            } else {  
                // 获得排名比thisPath前1位的节点  ,如果当前的节点不是序号最低的哪一个,就去当前序号的前一个,
                this.waitPath = \"/\" + groupNode + \"/\" + childrenNodes.get(index - 1);  
                // 在waitPath上注册监听器, 当waitPath被删除时, zookeeper会回调监听器的process方法  
                zk.getData(waitPath, true, new Stat());  
            }  
        }  
    }  

    private void doSomething() throws Exception {  
        try {  
            System.out.println(\"gain lock: \" + thisPath);  
            Thread.sleep(2000);  
            // do something  
        } finally {  
            System.out.println(\"finished: \" + thisPath);  
            // 将thisPath删除, 监听thisPath的client将获得通知  
            // 相当于释放锁  
            zk.delete(this.thisPath, -1);  
        }  
    }  

    public static void main(String[] args) throws Exception {  
        for (int i = 0; i < 10; i++) {  
            new Thread() {  
                public void run() {  
                    try {  
                        DistributedClient dl = new DistributedClient();  
                        dl.connectZookeeper();  
                    } catch (Exception e) {  
                        e.printStackTrace();  
                    }  
                }  
            }.start();  
        }  
        Thread.sleep(Long.MAX_VALUE);  
    }  
}

运行结果

进入连接zookeeper函数中
进入连接zookeeper函数中
进入连接zookeeper函数中
进入连接zookeeper函数中
进入连接zookeeper函数中
进入连接zookeeper函数中
进入连接zookeeper函数中
进入连接zookeeper函数中
进入连接zookeeper函数中
进入连接zookeeper函数中
SLF4J: Failed to load class \"org.slf4j.impl.StaticLoggerBinder\".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
thispath---/locks/sub0000000011
thispath---/locks/sub0000000012
thispath---/locks/sub0000000013
thispath---/locks/sub0000000014
thispath---/locks/sub0000000015
thispath---/locks/sub0000000016
thispath---/locks/sub0000000017
thispath---/locks/sub0000000018
thispath---/locks/sub0000000019
thispath---/locks/sub0000000020
开始判断节点个数
孩子节点个数大于1
当前节点--sub0000000011
开始判断节点个数
孩子节点个数大于1
当前节点--sub0000000012
开始判断节点个数
孩子节点个数大于1
当前节点--sub0000000013
开始判断节点个数
孩子节点个数大于1
当前节点--sub0000000014
开始判断节点个数
孩子节点个数大于1
当前节点--sub0000000015
开始判断节点个数
孩子节点个数大于1
当前节点--sub0000000017
开始判断节点个数
孩子节点个数大于1
当前节点--sub0000000016
开始判断节点个数
孩子节点个数大于1
当前节点--sub0000000018
开始判断节点个数
孩子节点个数大于1
当前节点--sub0000000019
开始判断节点个数
孩子节点个数大于1
当前节点--sub0000000020

Zookeeper下查看节点
\"在这里插入图片描述\"

收藏 打印