ZooKeeper distributed coordination service (node classification, event monitoring, java integration)

foreword

ZooKeeperis a distributed, open source distributed application coordination service, Googlean Chubbyopen source implementation of , Hadoopand Hbasean important component of . It is a software that provides consistent services for distributed applications. Its functions include: configuration maintenance, domain name service, distributed synchronization, group service, etc.

install start

Installation: Upload the zk installation package to the /opt directory, switch to the /opt directory, and execute the following commands

# 解压
tar -zxvf zookeeper-3.7.0-bin.tar.gz
# 重命名
mv apache-zookeeper-3.7.0-bin/ zookeeper
# 打开zookeeper根目录
cd /opt/zookeeper
# 创建一个数据目录,备用
mkdir data
# 打开zk的配置目录
cd /opt/zookeeper/conf
# copy配置文件,zk启动时会加载zoo.cfg文件
cp zoo_sample.cfg zoo.cfg
# 编辑配置文件
vim zoo.cfg
# 修改dataDir参数为之前创建的数据目录:/opt/zookeeper/data
# 切换到bin目录
cd /opt/zookeeper/bin
# 启动 
./zkServer.sh start
./zkServer.sh status # 查看启动状态
./zkServer.sh stop # 停止
./zkServer.sh restart # 重启
./zkCli.sh # 查看zk客户端

As follows, the startup is successful:

insert image description here

Related concepts

Zookeeper provides a multi-level node namespace (nodes are called znodes), each node is represented by a path separated by a slash (/), and each node has a parent node (except the root node), which is very similar to File system. And each node is unique.

There are four types of znode nodes:

  • PERSISTENT : Permanent node. After the client disconnects from zookeeper, the node still exists
  • EPHEMERAL : Ephemeral nodes. After the client disconnects from zookeeper, the node is deleted
  • PERSISTENT_SEQUENTIAL : permanent node, serialization. After the client disconnects from zookeeper, the node still exists, but Zookeeper sequentially numbers the node name
  • EPHEMERAL_SEQUENTIAL : Ephemeral nodes, serialization. After the client disconnects from zookeeper, the node is deleted, but Zookeeper sequentially numbers the node name

operation node

Create these four nodes:

[zk: localhost:2181(CONNECTED) 0] create /aa test  # 创建持久化节点
Created /aa
[zk: localhost:2181(CONNECTED) 1] create -s /bb test  # 创建持久序列化节点
Created /bb0000000001
[zk: localhost:2181(CONNECTED) 2] create -e /cc test  # 创建临时节点
Created /cc
[zk: localhost:2181(CONNECTED) 3] create -e -s /dd test  # 创建临时序列化节点
Created /dd0000000003
[zk: localhost:2181(CONNECTED) 4] ls /   # 查看某个节点下的子节点
[aa, bb0000000001, cc, dd0000000003, zookeeper]
[zk: localhost:2181(CONNECTED) 5] stat /  # 查看某个节点的状态
cZxid = 0x0
ctime = Thu Jan 01 08:00:00 CST 1970
mZxid = 0x0
mtime = Thu Jan 01 08:00:00 CST 1970
pZxid = 0x5
cversion = 3
dataVersion = 0
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 0
numChildren = 5
[zk: localhost:2181(CONNECTED) 6] get /aa  # 查看某个节点的内容
test
[zk: localhost:2181(CONNECTED) 11] delete /aa  # 删除某个节点
[zk: localhost:2181(CONNECTED) 7] ls /  # 再次查看
[bb0000000001, cc, dd0000000003, zookeeper]

event listener

When reading data, we can set event monitoring on the node at the same time. When the node data or structure changes, zookeeper will notify the client. Currently zookeeper monitors the following four events for nodes:

  1. Node creation: stat -w /xx

    When the /xx node is created: NodeCreated

  2. Node deletion: stat -w /xx

    When the /xx node is deleted: NodeDeleted

  3. Node data modification: get -w /xx

    When the /xx node data changes: NodeDataChanged

  4. Child node change: ls -w /xx

    When a child node of /xx node is created or deleted: NodeChildChanged

java client

ZooKeeperThere are java: native clients, ZkClient, and Curatorframeworks (similar to redisson, there are many functional packages).

  1. Introduce dependencies
<dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <version>3.7.0</version>
</dependency>
  1. Common APIs and their methods
public class ZkTest {
    
    

    public static void main(String[] args) throws KeeperException, InterruptedException {
    
    

        // 获取zookeeper链接
        CountDownLatch countDownLatch = new CountDownLatch(1);
        ZooKeeper zooKeeper = null;
        try {
    
    
            zooKeeper = new ZooKeeper("172.16.116.100:2181", 30000, new Watcher() {
    
    
                @Override
                public void process(WatchedEvent event) {
    
    
                    if (Event.KeeperState.SyncConnected.equals(event.getState()) 
                            && Event.EventType.None.equals(event.getType())) {
    
    
                        System.out.println("获取链接成功。。。。。。" + event);
                        countDownLatch.countDown();
                    }
                }
            });

            countDownLatch.await();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }

        // 创建一个节点,1-节点路径 2-节点内容 3-节点的访问权限 4-节点类型
        // OPEN_ACL_UNSAFE:任何人可以操作该节点
        // CREATOR_ALL_ACL:创建者拥有所有访问权限
        // READ_ACL_UNSAFE: 任何人都可以读取该节点
        // zooKeeper.create("/zktest/aa", "haha~~".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        zooKeeper.create("/test", "haha~~".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        // zooKeeper.create("/zktest/cc", "haha~~".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
        // zooKeeper.create("/zktest/dd", "haha~~".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        // zooKeeper.create("/zktest/dd", "haha~~".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        // zooKeeper.create("/zktest/dd", "haha~~".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);

        // 判断节点是否存在
        Stat stat = zooKeeper.exists("/test", true);
        if (stat != null){
    
    
            System.out.println("当前节点存在!" + stat.getVersion());
        } else {
    
    
            System.out.println("当前节点不存在!");
        }

        // 判断节点是否存在,同时添加监听
        zooKeeper.exists("/test", event -> {
    
    
        });

        // 获取一个节点的数据
        byte[] data = zooKeeper.getData("/zktest/ss0000000001", false, null);
        System.out.println(new String(data));

        // 查询一个节点的所有子节点
        List<String> children = zooKeeper.getChildren("/test", false);
        System.out.println(children);

        // 更新
        zooKeeper.setData("/test", "wawa...".getBytes(), stat.getVersion());

        // 删除一个节点
        //zooKeeper.delete("/test", -1);

        if (zooKeeper != null){
    
    
            zooKeeper.close();
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_43847283/article/details/128522950