zookeeper重要知识点

zookeeper重要知识点

文章目录

  • zookeeper重要知识点
    • 1、基本概念
      • 1.1、特点
      • 1.2、数据结构
      • 1.3、应用场景
      • 1.4、集群配置文件zoo.cfg
      • 1.5、节点类型
    • 2、选举机制
      • 2.1、第一次启动
      • 2.2、非第一次启动
    • 3、动态上下线
      • 3.1、代码
      • 3.2、测试
    • 4、分布式锁
      • 4.1、zookeeper分布式锁原理
      • 4.2、分布式锁代码基本实现


1、基本概念

1.1、特点

  • Zookeeper:一个领导者(Leader),多个跟随者(Follower)组成的集群。

  • 集群中只要有半数以上节点存活,Zookeeper集群就能正常服务。所以Zookeeper适合安装奇数台服务器。

  • 全局数据一致:每个Server保存一份相同的数据副本,Client无论连接到哪个Server,数据都是一致的。

  • 更新请求顺序执行,来自同一个Client的更新请求按其发送顺序依次执行。

  • 数据更新原子性,一次数据更新要么成功,要么失败。

  • 实时性,在一定时间范围内,Client能读到最新数据。

1.2、数据结构

ZooKeeper 数据模型的结构与Unix 文件系统很类似,整体上可以看作是一棵,每个节点称做一个ZNode。每一个ZNode 默认能够存储1MB 的数据,每个ZNode 都可以通过其路径唯一标识。

1.3、应用场景

提供的服务包括:统一命名服务统一配置管理统一集群管理服务器节点动态上下线软负载均衡分布式事务等。

1.4、集群配置文件zoo.cfg

server.2=192.168.149.133:1234:2345
server.3=192.168.149.134:1234:2345
server.4=192.168.149.135:1234:2345

参数解读:server.A=B:C:D

  • A是一个数字,表示这个是第几号服务器;集群模式下配置一个文件myid这个文件在 dataDir目录 下,这个文件里面有一个数据就是A的值, Zookeeper启动时读取此文件,拿到里面的数据与 zoo.cfg里面 的配置信息比较从而判断到底是哪个 server。

  • B是这个服务器的地址;

  • C是这个服务器 Follower与集群中的 Leader服务器交换信息的端口;

  • D是 万一集群中的 Leader服务器挂了,需要一个端口来重新进行选举,选出一个新的Leader,而这个端口就是用来执行选举时服务器相互通信的端口。

1.5、节点类型

(1)持久化目录节点
客户端与Zookeeper断开连接后,该节点依旧存在
(2)持久化顺序编号目录节点
客户端与Zookeeper断开连接后,该节点依旧存在,只是Zookeeper给该节点名称进行顺序编号
(3)临时目录节点
客户端与Zookeeper断开连接后,该节点被删除
(4)临时顺序编号目录节点
客户端与Zookeeper 断开连接后, 该节点被删除, 只是Zookeeper给该节点名称进行顺序编号。

2、选举机制

概念:

  • SID:服务器ID;也就是前面提到的myid文件的数字。

  • Zxid:事务ID。ZXID是一个事务ID,用来标识一次服务器状态的变更

  • Epoch:每个Leader任期的代号。没有Leader时同一轮投票过程中的逻辑时钟值是相同的。每投完一次票这个数据就会增加.

2.1、第一次启动

zookeeper服务器数量:5台

  • 服务1启动:发起一次选举,将票投给自己。但服务不是半数(3台服务)以上,此时服务1处于LOOKING状态。

  • 服务2启动:发起一次选举,此时服务1发现服务2的myid比自己大,于是将票投给了服务2,服务2也投给自己。此时服务1持有0票,服务2持有2票,但仍未超过半数服务,服务1和服务2处于LOOKING状态。

  • 服务3启动:发起一次选举,同理服务1和服务2发现服务3myid较大,投票给服务3,服务3将票投给自己。此时服务1和服务2持有0票,服务3持有3票,超过半数,服务3为LEADING,服务1和服务2为FOLLWING。

  • 服务4启动:发起一次选举,此时服务1、2、3已经不是LOOKING状态,而是正常运行,不会更改选举信息,服务4投给自己一票。此时服务1、2为0票,服务3为3票,服务4为1票,服务4服从多数为FOLLWING。

  • 服务5启动:发起一次选举,此时服务1、2、3、4已经不是LOOKING状态而是正常运行,不会更改选举信息,服务5投给自己一票。此时服务1、2为0票,服务3为3票,服务4、5为1票,服务5服从多数为FOLLWING。

2.2、非第一次启动

接着上面进行分析,分两种情况。

1、follow宕机

​ 对于第一种已经存在Leader的情况,机器试图去选举Leader时,会被告知当前服务器的Leader信息,对于该机器来说,仅需要和Leader机器建立连接,并进行状态同步即可。

2、leader宕机

假设ZooKeeper由5台服务器组成,SID分别为1、2、3、4、5,ZXID分别为8、8、8、7、7,并且此时SID为3的服务器是Leader。某一时刻,3和5服务器出现故障,因此开始进行Leader选举。

此时服务1信息为:SID:1;ZXID:8;Epoch:1;
此时服务2信息为:SID:2;ZXID:8;Epoch:1;
此时服务4信息为:SID:4;ZXID:7;Epoch:1;

选举Leader方式:

​ 1、EPOCH大的直接胜出。

​ 2、EPOCH相同,则事务id大的胜出。

​ 3、事务id相同,服务器id大的胜出。

将上述场景带入得:服务器2当选leader。

3、动态上下线

3.1、代码

场景:某分布式系统中,主节点可以有多台,可以动态上下线,任意一台客户端都能实时感知到主节点服务器的上下线。
其实服务注册到zookeeper就相当于一个节点,监控的就是服务的状态,是否宕机或者正常启动。

代码如下:

public class ClientZookeeper {
    //zookeeper集群连接信息
    private static String connectString = "192.168.149.135:2181,192.168.149.141:2181,192.168.149.138:2181";
    //session时间
    private static int sessionTimeout = 2000;
    //zookeeper操作类
    private ZooKeeper zkClient = null;

    /**
     * 连接zookeeper,以及监控的回调方法。
     *
     * @throws IOException
     */
    private void getConnect() throws IOException {

        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {

            public void process(WatchedEvent event) {

                try {

                    getChildren();
                } catch (KeeperException e) {

                    e.printStackTrace();
                } catch (InterruptedException e) {

                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 监控回调调用该方法,查询节点信息
     *
     * @throws KeeperException
     * @throws InterruptedException
     */
    private void getChildren() throws KeeperException, InterruptedException {

        List<String> children = zkClient.getChildren("/servers", true);
        // 存储服务器节点主机名称集合
        ArrayList<String> hosts = new ArrayList<String>();
        for (String child : children) {

            byte[] data = zkClient.getData("/servers/" + child, false, null);
            hosts.add(new String(data));
        }
        System.out.println(hosts);
    }

    private void business() throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE);
    }

    /**
     * 测试方法
     *
     * @throws KeeperException
     * @throws InterruptedException
     * @throws IOException
     */
    @Test
    public void clientZookeeper() throws KeeperException, InterruptedException, IOException {
        // 1.连接zookeeper集群
        this.getConnect();
        // 2.注册监听
        this.getChildren();
        // 3.业务逻辑处理
        this.business();
    }

}

3.2、测试

1、在zookeeper创建一个servers节点。

2、启动测试类,观察控制台输出。

3、在zookeeper上/servers下创建节点(模拟上线)

create -e -s /servers/test01 "嘿嘿黑"

4、代码调用了回调方法,执行getChildren方法,打印了节点信息。

20:49:10.310 [main-SendThread(192.168.149.138:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Reading reply sessionid:0x40000013d090001, packet:: clientPath:null serverPath:null finished:false header:: 4,4  replyHeader:: 4,25769803790,0  request:: '/servers/test0000000003,F  response:: #ffffffe5ffffff98ffffffbfffffffe5ffffff98ffffffbfffffffe5ffffff98ffffffbfffffffe2ffffff80ffffff9c,s{25769803790,25769803790,1652446150286,1652446150286,0,0,0,0,12,0,25769803790} 
[嘿嘿嘿]
20:49:11.639 [main-SendThread(192.168.149.138:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Got ping response for sessionid: 0x40000013d090001 after 1ms

5、将test01节点删除,观察控制台(模拟下线)

控制台输出:

20:50:54.103 [main-SendThread(192.168.149.138:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Reading reply sessionid:0x40000013d090001, packet:: clientPath:null serverPath:null finished:false header:: 5,8  replyHeader:: 5,25769803791,0  request:: '/servers,T  response:: v{} 
[]
20:50:55.433 [main-SendThread(192.168.149.138:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Got ping response for sessionid: 0x40000013d090001 after 1ms

4、分布式锁

4.1、zookeeper分布式锁原理

  • ZooKeeper节点递增有序性,可以确保锁的公平。
  • ZooKeeper的节点监听机制,可以保障占有锁的传递有序而且高效。
  • ZooKeeper的节点监听机制,能避免羊群效应

4.2、分布式锁代码基本实现

@Slf4j
public class DistributedLock {
    // zookeeper server 列表
    private static String connectString = "192.168.149.135:2181,192.168.149.142:2181,192.168.149.138:2181";
    // 超时时间
    private int sessionTimeout = 20000;
    private String rootNode = "locks";
    private String subNode = "seq-";
    // 当前client 等待的子节点
    private String waitPath;
    //ZooKeeper 连接
    private CountDownLatch connectLatch = new CountDownLatch(1);
    //ZooKeeper 节点等待
    private CountDownLatch waitLatch = new CountDownLatch(1);
    // 当前 client 创建的子节点
    private String currentNode;
    private ZooKeeper zkClient = null;

    //利用原子类,保证锁的重入性
    private AtomicInteger atomicInteger = new AtomicInteger(0);
    //保存正在持有锁的线程。
    private transient Thread thread;

    public DistributedLock() throws IOException, InterruptedException, KeeperException {
        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            //监视器回调方法
            public void process(WatchedEvent event) {
                // 连接建立时 , 打开 latch, 唤醒 wait 在该 latch 上的线程
                if (event.getState() == Event.KeeperState.SyncConnected) {
                    connectLatch.countDown();
                }
                // 发生了 waitPath 的删除事件
                if (event.getType() == Event.EventType.NodeDeleted && event.getPath().equals(waitPath)) {
                    waitLatch.countDown();
                }
            }
        });

        connectLatch.await();
        // 获取根节点状态
        Stat stat = zkClient.exists("/" + rootNode, false);
        //如果根节点不存在,则创建根节点,根节点类型为永久节点
        if (stat == null) {
            System.out.println(" 根节点不存在");
            zkClient.create("/" + rootNode, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
    }


    // 加锁方法
    public void zkLock() {
        try {
            //判断是否是重入线程,若是则不需要再次创建节点。
            if (atomicInteger.get() == 0) {
                //无需阻塞,没有线程占有锁,对全局变量赋值,并且atomicInteger+1
                thread = Thread.currentThread();
                atomicInteger.incrementAndGet();
                currentNode = zkClient.create("/" + rootNode + "/" + subNode, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
            } else {
                if (!thread.equals(Thread.currentThread())) {
                    currentNode = zkClient.create("/" + rootNode + "/" + subNode, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
                }else {
                    //无需阻塞,当前线程持有锁,对全局变量赋值,并且atomicInteger+1
                    atomicInteger.incrementAndGet();
                    thread = Thread.currentThread();
                }
            }
            // 在根节点下创建临时顺序节点,返回值为创建的节点路径
            // wait 一小会 , 让结果更清晰一些
            Thread.sleep(10);

            List<String> childrenNodes = zkClient.getChildren("/" + rootNode, false);
            log.info("childrenNodes的值为{}", childrenNodes);
            if (childrenNodes.size() == 1) {
                //如果size为1,说明就是当前线程的节点,直接返回无需阻塞
                //无需阻塞,当前线程持有锁,对全局变量赋值,并且atomicInteger+1
                return;
            } else {
                //对根节点下的所有临时顺序节点进行从小到大排序
                Collections.sort(childrenNodes);
                String substring = currentNode.substring(("/" + rootNode + "/").length());
                int index = childrenNodes.indexOf(substring);
                if (index == 0) {
                    //说明 thisNode 在列表中最小 , 当前client 获得锁
                    return;
                } else if (index == -1) {
                    log.info("数据异常");
                } else {
                    // 获得排名比 currentNode 前 1 位的节点
                    this.waitPath = "/" + rootNode + "/" + childrenNodes.get(index - 1);
                    log.info("this.waitPath值为:{}", this.waitPath);
                    // 在 waitPath 上注册监听器 , 当 waitPath 被删除时 ,zookeeper 会回调监听器的 process 方法
                    zkClient.getData(waitPath, true, new Stat());
                    //进入等待锁状态
                    waitLatch.await();
                    return;
                }
            }
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    // 解锁方法
    public void zkUnlock() {
        try {
            //如果atomicInteger为0则说明线程全部释放,否则有重入线程未释放锁,不可删除节点
            if (atomicInteger.decrementAndGet() == 0) {
                zkClient.delete(this.currentNode, -1);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }
    }

    //测试方法
    public static void main(String[] args) throws InterruptedException, IOException, KeeperException {
        // 创建分布式锁 1
        final DistributedLock lock1 = new DistributedLock();
        // 创建分布式锁 2
        final DistributedLock lock2 = new DistributedLock();

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 获取锁对象
                try {
                    lock1.zkLock();
                    lock1.zkLock();//重入锁
                    log.info("线程1获取锁");
                    Thread.sleep(3 * 1000);
                    lock1.zkUnlock();
                    lock1.zkUnlock();
                    System.out.println(" 线程 1 释放锁");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        Thread.sleep(1 * 1000);
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 获取锁对象
                try {
                    lock2.zkLock();
                    System.out.println(" 线程 2 获取锁");
                    Thread.sleep(3 * 1000);
                    lock2.zkUnlock();
                    System.out.println(" 线程 2 释放锁");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}

控制台打印:

 线程 1 获取锁
 线程 1 释放锁
 线程 2 获取锁
 线程 2 释放锁

你可能感兴趣的:(SpringCloud)