【zookeeper CuratorFramework实现服务发现】 1.TreeCache+TreeCacheListener

pom.xml

        
        
            org.apache.curator
            curator-framework
            4.0.0
        
        
            org.apache.curator
            curator-recipes
            4.0.0
        

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.ChildData;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;

@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("根节点已经存在");
        }

        // 监听节点的变化
        TreeCache treeCache = new TreeCache(cf, "/game-nodes");
        TreeCacheListener listener = (curatorFramework, event) -> {
            ChildData data = event.getData();
            boolean change = true;

            if (data != null) {
                log.info("改变的路径path={} 事件type={} data={}", event.getData().getPath(), event.getType(), new String(event.getData().getData()));

                switch (event.getType()) {
                    case NODE_ADDED:
                        break;
                    case NODE_UPDATED:
                        break;
                    case NODE_REMOVED:
                        break;
                    default:
                        change = false;
                        break;
                }
            } else {
                change = false;
                log.info("事件type={}", event.getType());
            }


            if (change) {
                System.out.println();
                // 获取所有的游戏服节点列表
                List 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();
            }
        };
        treeCache.getListenable().addListener(listener);
        treeCache.start();

        System.in.read();
    }
}

/*
参考: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层节点树就够了,这样子可以获取服务器列表之类的。

你可能感兴趣的:(#,zookeeper,zookeeper)