zookeeper CuratorFramework实现服务发现

发布时间:2024年01月02日

pom.xml

        <!--zk-->
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-framework</artifactId>
            <version>4.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-recipes</artifactId>
            <version>4.0.0</version>
        </dependency>

1.Gateway.java

package org.example.testZk;

import java.nio.charset.StandardCharsets;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

@Slf4j
public class Gateway {

    public static void main(String[] args) throws Exception {
        // 启动zk
        CuratorFramework cf = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181").sessionTimeoutMs(4000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();

        cf.start();

        // 打印下状态
        log.info("zk启动状态:{}", cf.getState());

        // 创建持久节点:游戏服列表根节点
        if (cf.checkExists().forPath("/game-nodes") == null) {
            log.info("持久节点不存在,创建下");
            cf.create().forPath("/game-nodes", "".getBytes(StandardCharsets.UTF_8));
        } else {
            log.info("根节点已经存在");
        }


        // 监听节点的变化
        PathChildrenCache childrenCache = new PathChildrenCache(cf, "/game-nodes", true);

        PathChildrenCacheListener listener = (curatorFramework, event) -> {
            log.info("改变的路径path={} 事件type={} data={}", event.getData().getPath(), event.getType(), new String(event.getData().getData()));

            switch (event.getType()) {
                case CONNECTION_RECONNECTED:
                case CHILD_ADDED:
                    break;
                case CHILD_UPDATED:
                    break;
                case CONNECTION_LOST:
                case CHILD_REMOVED:
                    break;
                default:
                    log.error("未处理的操作type={}", event.getType());
                    break;
            }

            System.out.println();
            // 获取所有的游戏服节点列表
            List<String> serverList = cf.getChildren().forPath("/game-nodes");
            if (!serverList.isEmpty()) {
                for (String gameNodeName : serverList) {
                    String hostPort = new String(cf.getData().forPath("/game-nodes/" + gameNodeName));
                    log.info("游戏服{} 地址信息:{}", gameNodeName, hostPort);
                }
            } else {
                log.info("服务器列表为空");
            }

            System.out.println();
        };
        childrenCache.getListenable().addListener(listener);
        childrenCache.start();

        System.in.read();
    }
}

/*
11:22:43.777 [main] INFO org.example.testZk.Gateway -- 持久节点不存在,创建下
11:22:49.628 [Curator-PathChildrenCache-0] INFO org.example.testZk.Gateway -- 改变的路径path=/game-nodes/game-node-1 事件type=CHILD_ADDED data=127.0.0.1:6000
11:26:09.772 [Curator-PathChildrenCache-0] INFO org.example.testZk.Gateway -- 游戏服game-node-1 地址信息:127.0.0.1:6000
11:22:54.267 [Curator-PathChildrenCache-0] INFO org.example.testZk.Gateway -- 改变的路径path=/game-nodes/game-node-1 事件type=CHILD_REMOVED data=127.0.0
.1:6000
11:26:19.083 [Curator-PathChildrenCache-0] INFO org.example.testZk.Gateway -- 服务器列表为空


参考:https://blog.csdn.net/ytangdigl/article/details/108593958
 */

2.GameNode.java

package org.example.testZk;

import java.nio.charset.StandardCharsets;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

@Slf4j
public class GameNode {

    public static void main(String[] args) throws Exception {
        // 启动zk
        CuratorFramework cf = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181").sessionTimeoutMs(4000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();

        cf.start();

        // 打印下状态
        log.info("zk启动状态:{}", cf.getState());

        // 创建持久节点:游戏服列表根节点
        if (cf.checkExists().forPath("/game-nodes") == null) {
            log.info("持久节点不存在,创建下");
            cf.create().forPath("/game-nodes", "".getBytes(StandardCharsets.UTF_8));
        } else {
            log.info("根节点已经存在");
        }

        // 创建临时节点(存在则删除)
        String addNodePath = "/game-nodes/game-node-1";
        if (cf.checkExists().forPath(addNodePath) != null) {
            cf.delete().forPath(addNodePath);
        }
        cf.create().withMode(CreateMode.EPHEMERAL).forPath(addNodePath, "127.0.0.1:6000".getBytes(StandardCharsets.UTF_8));

        System.in.read();
    }
}

/*
11:26:09.747 [main] INFO org.example.testZk.GameNode -- 根节点已经存在
 */

思考:

zk中我们往往是:2层节点树就够了,这样子可以获取服务器列表之类的。

文章来源:https://blog.csdn.net/themagickeyjianan/article/details/135336893
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。