← 返回学习路线

SYSTEM

监听机制

Java基础监听机制system
src/content/notes/system/监听机制.md

监听机制

实现原理

ZooKeeper 中引入了 Watcher 机制来实现了发布/订阅功能,客户端注册监听目录节点,在特定事件触发时,ZooKeeper 会通知所有关注该事件的客户端,保证 ZooKeeper 保存的任何的数据的任何改变都能快速的响应到监听应用程序

监听命令:只能生效一次,接收一次通知,再次监听需要重新注册

ls –w /path					# 监听【子节点数量】的变化
get –w /path				# 监听【节点数据】的变化

工作流程:

  • 在主线程中创建 Zookeeper 客户端,这时就会创建两个线程,一个负责网络连接通信(connet),一个负责监听(listener)
  • 通过 connect 线程将注册的监听事件发送给 Zookeeper
  • 在 Zookeeper 的注册监听器列表中将注册的监听事件添加到列表中
  • Zookeeper 监听到有数据或路径变化,将消息发送给 listener 线程
  • listener 线程内部调用 process() 方法

Curator 框架引入了 Cache 来实现对 ZooKeeper 服务端事件的监听,三种 Watcher:

  • NodeCache:只是监听某一个特定的节点
  • PathChildrenCache:监控一个 ZNode 的子节点
  • TreeCache:可以监控整个树上的所有节点,类似于 PathChildrenCache 和 NodeCache 的组合

监听案例

整体架构

客户端实时监听服务器动态上下线


代码实现

客户端:先启动客户端进行监听

public class DistributeClient {
    private String connectString = "192.168.3.128:2181";
    private int sessionTimeout = 20000;
    private ZooKeeper zk;

    public static void main(String[] args) throws Exception {
        DistributeClient client = new DistributeClient();
        
        // 1 获取zk连接
        client.getConnect();

        // 2 监听/servers下面子节点的增加和删除
        client.getServerList();

        // 3 业务逻辑
        client.business();
    }

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

    private void getServerList() throws KeeperException, InterruptedException {
        ArrayList<String> servers = new ArrayList<>();
        // 获取所有子节点,true 代表触发监听操作
        List<String> children = zk.getChildren("/servers", true);

        for (String child : children) {
            // 获取子节点的数据
            byte[] data = zk.getData("/servers/" + child, false, null);
            servers.add(new String(data));
        }
        System.out.println(servers);
    }

    private void getConnect() throws IOException {
        zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                getServerList();
            }
        });
    }
}

服务端:启动时需要 Program arguments

public class DistributeServer {
    private String connectString = "192.168.3.128:2181";
    private int sessionTimeout = 20000;
    private ZooKeeper zk;

    public static void main(String[] args) throws Exception {
        DistributeServer server = new DistributeServer();

        // 1 获取 zookeeper 连接
        server.getConnect();

        // 2  注册服务器到 zk 集群,注意参数
        server.register(args[0]);

        // 3 启动业务逻辑
        server.business();
    }

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

    private void register(String hostname) throws KeeperException, InterruptedException {
        // OPEN_ACL_UNSAFE: ACL 开放
        // EPHEMERAL_SEQUENTIAL: 临时顺序节点
        String create = zk.create("/servers/" + hostname, hostname.getBytes(),
                                  ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(hostname + " is online");
    }

    private void getConnect() throws IOException {
        zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
            }
        });
    }
}