zookeeper

文章目录

  • 前言
  • 一、为什么需要zookeeper?
  • 二、zookeeper的特点
  • 三 zookeeper架构图
  • 四 zookeeper作用
  • 五 zookeeper安装和配置
    • 1 安装
    • 2 配置
  • 六 zookeeper的zndoe节点
  • 七 命令
    • 1 常用命令
    • 2 高级命令
    • 3 Watcher机制
  • 八 ACL权限控制(五种)
  • 九 代码实操
    • 0 pom依赖 引入 参考结构
    • 1 简单的链接
    • 2 对zk的增删改查
    • 3 处理watcher事件(与2 的不同主要是wather的改变)
    • 4 使用apache curator操作zk


前言

zookeeper入门

一、为什么需要zookeeper?

zookeeper_第1张图片
zookeeper_第2张图片

雅虎的很多大型系统软件都由动物(dog,cat)命名
而zookeeper(动物园)相当于这些软件系统的分布式协调框架

二、zookeeper的特点

zookeeper_第3张图片
zookeeper_第4张图片

三 zookeeper架构图

zookeeper_第5张图片
Leader死后很快能进行重新选举

四 zookeeper作用

zookeeper_第6张图片
zookeeper_第7张图片

五 zookeeper安装和配置

1 安装

https://downloads.apache.org/zookeeper/zookeeper-3.6.3/
进入网址选择复制连接
然后进入Linux下
wget + 链接
在这里插入图片描述
下载好后输入如下命令进行解压
tar zxvf apache-zookeeper-3.6.3-bin.tar.gz
在这里插入图片描述
在这里插入图片描述

2 配置

首先进入目录下复制一份配置文件
zookeeper_第8张图片

[root@iZuf6bsml3xp6lqbtvsilzZ apache-zookeeper-3.6.3-bin]# cp conf/zoo_sample.cfg conf/zoo.cfg
[root@iZuf6bsml3xp6lqbtvsilzZ apache-zookeeper-3.6.3-bin]# cd conf
[root@iZuf6bsml3xp6lqbtvsilzZ conf]# ls
configuration.xsl  log4j.properties  zoo.cfg  zoo_sample.cfg
[root@iZuf6bsml3xp6lqbtvsilzZ conf]# 

简单观察配置文件
zookeeper_第9张图片
停止命令 启动命令stop换为start
在这里插入图片描述

六 zookeeper的zndoe节点

zookeeper_第10张图片
zookeeper_第11张图片
zookeeper_第12张图片
zookeeper_第13张图片

七 命令

1 常用命令

启动服务端
[root@iZuf6bsml3xp6lqbtvsilzZ apache-zookeeper-3.6.3-bin]# ./bin/zkServer.sh start

启动客户端
[root@iZuf6bsml3xp6lqbtvsilzZ apache-zookeeper-3.6.3-bin]# ./bin/zkCli.sh -server 127.0.0.1:2181

简单的zode 增删改查操作
[zk: 127.0.0.1:2181(CONNECTED) 2] ls -R /
/
/zookeeper
/zookeeper/config
/zookeeper/quota
[zk: 127.0.0.1:2181(CONNECTED) 3] create /java1
Created /java1
[zk: 127.0.0.1:2181(CONNECTED) 4] set /java1 data1
[zk: 127.0.0.1:2181(CONNECTED) 5] get /java1
data1
[zk: 127.0.0.1:2181(CONNECTED) 6] ls -R /
/
/java1
/zookeeper
/zookeeper/config
/zookeeper/quota
[zk: 127.0.0.1:2181(CONNECTED) 7] 


2 高级命令

zookeeper_第14张图片
zookeeper_第15张图片

[zk: 127.0.0.1:2181(CONNECTED) 12] stat /java1
cZxid = 0x2
ctime = Tue Apr 19 11:05:07 CST 2022
mZxid = 0x5
mtime = Tue Apr 19 11:18:39 CST 2022
pZxid = 0x2
cversion = 0
dataVersion = 2
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 3
numChildren = 0

版本号操作set更改
[zk: 127.0.0.1:2181(CONNECTED) 13] set /java1 qqqq -v2
[zk: 127.0.0.1:2181(CONNECTED) 14] set /java1 qqqqq -v2
version No is not valid : /java1

创建临时节点
[zk: 127.0.0.1:2181(CONNECTED) 15] create /java1/test1 -e
Created /java1/test1
[zk: 127.0.0.1:2181(CONNECTED) 16] stat /java1/test1
cZxid = 0x8
ctime = Tue Apr 19 11:21:22 CST 2022
mZxid = 0x8
mtime = Tue Apr 19 11:21:22 CST 2022
pZxid = 0x8
cversion = 0
dataVersion = 0
aclVersion = 0
ephemeralOwner = 0x100690cbce20000
dataLength = 0
numChildren = 0

//创建这个节点同时为临时节点和顺序节点
[zk: 127.0.0.1:2181(CONNECTED) 17] create /java1/test1 -e -s
Created /java1/test10000000001
[zk: 127.0.0.1:2181(CONNECTED) 18]

3 Watcher机制

zookeeper_第16张图片
zookeeper_第17张图片

八 ACL权限控制(五种)

zookeeper_第18张图片
zookeeper_第19张图片
zookeeper_第20张图片

九 代码实操

0 pom依赖 引入 参考结构


    
      org.apache.zookeeper
      zookeeper
      3.6.0
    
    
      org.apache.curator
      curator-framework
      2.12.0
    
    
      org.apache.curator
      curator-recipes
      2.12.0
    
  

1 简单的链接

package com.imooc.zkjavaapi;

/**
 * 描述:     ZK常量
 */
public class ZkConstant {

    public static final String ZK_HOST = "127.0.0.1:2181";

    public static final Integer CONNECT_TIMEOUT = 3000;
    public static final String PATH1 = "/imooc-my-first-node";

}
package com.imooc.zkjavaapi.watcher;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;

/**
 * 描述:     连接Watcher
 */
public class ConnectWatcher implements Watcher {

    @Override
    public void process(WatchedEvent event) {
        System.out.println("ConnectWatcher的process被调用了");
        if (event.getState()== KeeperState.SyncConnected) {
            System.out.println("连接成功");
        }
        if (event.getState()== KeeperState.Closed) {
            System.out.println("连接关闭");
        }
    }
}
package com.imooc.zkjavaapi;

import com.imooc.zkjavaapi.watcher.ConnectWatcher;
import java.io.IOException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooKeeper.States;

/**
 * 描述:     连接到ZK
 */
public class FirstConnect {

    public static void main(String[] args) throws IOException, InterruptedException {
        //创建watcher对象
        ConnectWatcher connectWatcher = new ConnectWatcher();
        //new zk对象
        ZooKeeper zk = new ZooKeeper(ZkConstant.ZK_HOST, ZkConstant.CONNECT_TIMEOUT, connectWatcher);
        System.out.println("客户端开始连接ZK服务器");
        States state = zk.getState();
        System.out.println(state);
        Thread.sleep(2000);
        state = zk.getState();
        System.out.println(state);
        Thread.sleep(2000);
        zk.close();
    }
}

2 对zk的增删改查

package com.imooc.zkjavaapi;

/**
 * 描述:     ZK常量
 */
public class ZkConstant {

    public static final String ZK_HOST = "127.0.0.1:2181";

    public static final Integer CONNECT_TIMEOUT = 3000;
    public static final String PATH1 = "/imooc-my-first-node";

}
package com.imooc.zkjavaapi.watcher;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;

/**
 * 描述:     连接Watcher
 */
public class ConnectWatcher implements Watcher {

    @Override
    public void process(WatchedEvent event) {
        System.out.println("ConnectWatcher的process被调用了");
        if (event.getState()== KeeperState.SyncConnected) {
            System.out.println("连接成功");
        }
        if (event.getState()== KeeperState.Closed) {
            System.out.println("连接关闭");
        }
    }
}

package com.imooc.zkjavaapi;

import com.imooc.zkjavaapi.watcher.ConnectWatcher;
import java.io.IOException;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooKeeper.States;

/**
 * 描述:     对节点的增删改查
 */
public class ZkCRUD {

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        ConnectWatcher connectWatcher = new ConnectWatcher();
        ZooKeeper zk = new ZooKeeper(ZkConstant.ZK_HOST, ZkConstant.CONNECT_TIMEOUT, connectWatcher);
        System.out.println("客户端开始连接ZK服务器");
        States state = zk.getState();
        System.out.println(state);
        Thread.sleep(2000);
        state = zk.getState();
        System.out.println(state);
        Thread.sleep(2000);

        //对节点进行增删改查
        zk.create(ZkConstant.PATH1, "imooc1".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        Thread.sleep(2000);
        byte[] data = null;
        data = zk.getData(ZkConstant.PATH1, null, null);
        System.out.println(new String(data));
        Thread.sleep(2000);
        zk.setData(ZkConstant.PATH1, "imooc2".getBytes(), -1);
        Thread.sleep(2000);
        data = zk.getData(ZkConstant.PATH1, null, null);
        System.out.println(new String(data));
        zk.delete(ZkConstant.PATH1, -1);

        zk.close();
    }
}

3 处理watcher事件(与2 的不同主要是wather的改变)

1 watcher

package com.imooc.zkjavaapi.watcher;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;

public class DataChangedWatcher implements Watcher {

    @Override
    public void process(WatchedEvent event) {
        System.out.println("DataChangedWatcher的process被调用了");
        if (event.getType()== EventType.NodeDataChanged) {
            System.out.println("数据被改变");
        }
        if (event.getType()== EventType.NodeDeleted) {
            System.out.println("节点已删除");
        }
    }
}

2 主要代码

package com.imooc.zkjavaapi;

import com.imooc.zkjavaapi.watcher.ConnectWatcher;
import com.imooc.zkjavaapi.watcher.DataChangedWatcher;
import java.io.IOException;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooKeeper.States;

/**
 * 描述:     ZK节点改变、删除事件的监听
 */
public class ZkWatcher {

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        DataChangedWatcher dataChangedWatcher = new DataChangedWatcher();
        ZooKeeper zk = new ZooKeeper(ZkConstant.ZK_HOST, ZkConstant.CONNECT_TIMEOUT, dataChangedWatcher);
        System.out.println("客户端开始连接ZK服务器");
        States state = zk.getState();
        System.out.println(state);
        Thread.sleep(2000);
        state = zk.getState();
        System.out.println(state);
        Thread.sleep(2000);

        zk.create(ZkConstant.PATH1, "imooc1".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        Thread.sleep(2000);
        byte[] data = null;
        //watcher设置为true,代表可以监听对应的事件
        data = zk.getData(ZkConstant.PATH1, true, null);
        System.out.println(new String(data));
        Thread.sleep(2000);
        zk.setData(ZkConstant.PATH1, "imooc2".getBytes(), -1);
        Thread.sleep(2000);
        data = zk.getData(ZkConstant.PATH1, true, null);
        System.out.println(new String(data));
        zk.delete(ZkConstant.PATH1, -1);

        zk.close();
    }
}

需要的一些常量

package com.imooc.zkjavaapi;

/**
 * 描述:     ZK常量
 */
public class ZkConstant {

    public static final String ZK_HOST = "127.0.0.1:2181";

    public static final Integer CONNECT_TIMEOUT = 3000;
    public static final String PATH1 = "/imooc-my-first-node";

}

4 使用apache curator操作zk

创传统的java api写法复杂
功能不强
zookeeper_第21张图片


    
      org.apache.curator
      curator-framework
      2.12.0
    
    
      org.apache.curator
      curator-recipes
      2.12.0
    

代码实现

package com.imooc.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher.Event.EventType;

/**
 * 描述:     用Curator来操作ZK
 */
public class CuratorTests {

    public static void main(String[] args) throws Exception {
        //链接字符串
        String connectString = "127.0.0.1:2181";
        //路径
        String path = "/curator1";
        //设置重连操作
        ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1000, 10);
        //使用 1链接字符串  2设置重连操作 创建连接对象client
        CuratorFramework client = CuratorFrameworkFactory.newClient(connectString, retry);
        //开启连接对象
        client.start();

        client.getCuratorListenable().addListener((CuratorFramework c, CuratorEvent event) -> {
            switch (event.getType()) {
                case WATCHED:
                    WatchedEvent watchedEvent = event.getWatchedEvent();
                    if (watchedEvent.getType() == EventType.NodeDataChanged) {
                        System.out.println(new String(c.getData().forPath(path)));
                        System.out.println("触发事件");
                    }
            }
        });
        String data = "test";
        String data2 = "test2";
        //用连接对象创建节点  节点类型为临时节点(withMode)forpath是节点路径 Data是设置该节点的数据
        client.create().withMode(CreateMode.EPHEMERAL).forPath(path, data.getBytes());

        //根据Path获得节点数据 并且使用watched开启监听
        byte[] bytes = client.getData().watched().forPath(path);
        System.out.println(new String(bytes));
        
        //根据Path重新设置数据
        client.setData().forPath(path, data2.getBytes());
        Thread.sleep(2000);
        client.delete().forPath(path);
        Thread.sleep(2000);

        //永久监听
        String pathNew = "/curatorNew";
        client.create().withMode(CreateMode.EPHEMERAL).forPath(pathNew, data.getBytes());

        NodeCache nodeCache = new NodeCache(client, pathNew);
        nodeCache.start();
        nodeCache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                ChildData currentData = nodeCache.getCurrentData();
                if (currentData != null) {
                    System.out.println("触发了永久监听的回调,当前值为:" + new String(currentData.getData()));
                }
            }
        });
        client.setData().forPath(pathNew, data2.getBytes());
        Thread.sleep(2000);
        client.setData().forPath(pathNew, data2.getBytes());
        Thread.sleep(2000);
        client.setData().forPath(pathNew, data2.getBytes());
        Thread.sleep(2000);
        client.delete().forPath(pathNew);
    }
}

你可能感兴趣的:(java,分布式)