Zookeeper 服务器上线客户端动态感知

 

主要参考的是 https://www.cnblogs.com/dengpengbo/p/10443547.html 

B站有个视频可以当做zookeeper入门。

服务器集群中有可能有些服务器会宕机,客户端需要尽快知道哪些服务是可用的。

整个流程主要是服务器上线以后往zookeeper 增加server节点。例如在/Server 下增加临时序列节点

这样A服务上线,就会增加/Servers/Servers0000001 保持的值就是当前服务器的ip等信息

B服务器上线就会增加/Servers/Servers0000001

而临时节点在服务器下线以后就会从zookeeper删除.

在客户端可以监听/Servers 的节点变化,如果增加则去获取节点的值。

在这里插入图片描述

在这里插入图片描述

 

package com.learning.zookeeper;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;

public class DistributeServer implements Watcher {

    private CountDownLatch countDownLatch = new CountDownLatch(1);
    private static final int SESSION_TIMEOUT = 2000;
    private ZooKeeper zooKeeper;


    private static final String PARRENT_NODE = "/servers";
    public static void main(String[] args) throws Exception{
        DistributeServer distributeServer = new DistributeServer(args[0]);
        distributeServer.registerServer(args[1]);

        Scanner sc = new Scanner(System.in);
        while(true){
            if("exit".equalsIgnoreCase(sc.nextLine())){
                break;
            }
        }

        distributeServer.closeConnection();
    }

    public DistributeServer(String host) throws Exception {
        connectZk(host);
    }

    public String getData(String path) throws Exception{
        byte[] result =  zooKeeper.getData(path,false,null);
        return result == null ? "":new String(result);
    }

    private void connectZk(String zkServerHost) throws InterruptedException, IOException {

        zooKeeper = new ZooKeeper(zkServerHost, SESSION_TIMEOUT, this);
        countDownLatch.await();
    }

    public void process(WatchedEvent watchedEvent) {
        if(watchedEvent.getState() == Event.KeeperState.SyncConnected){
            //链接成功
            System.out.println("链接成功");
            countDownLatch.countDown();


        }
    }



    public void registerServer(String host) throws Exception{
        if(zooKeeper.exists(PARRENT_NODE,false) == null){
            zooKeeper.create(PARRENT_NODE,"allServer".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
        zooKeeper.create(PARRENT_NODE+"/server",host.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);//临时有序节点
    }

    public void closeConnection() throws InterruptedException {
        if(zooKeeper != null){
            zooKeeper.close();
            System.out.println("链接关闭");
        }
    }

}
package com.learning.zookeeper;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;

public class DistributeClient implements Watcher {

    private CountDownLatch countDownLatch = new CountDownLatch(1);
    private static final int SESSION_TIMEOUT = 20000;
    private ZooKeeper zooKeeper;
    private volatile List<String> serverList;
    private static final String PARRENT_NODE = "/servers";
    public DistributeClient(String host) throws Exception {
        connectZk(host);
    }

    public String getData(String path) throws Exception{
        byte[] result =  zooKeeper.getData(path,false,null);
        return result == null ? "":new String(result);
    }

    private void connectZk(String zkServerHost) throws InterruptedException, IOException {

        zooKeeper = new ZooKeeper(zkServerHost, SESSION_TIMEOUT, this);
        countDownLatch.await();
    }
    public static void main(String[] args) throws Exception{
        DistributeClient distributeClient = new DistributeClient(args[0]);
        Scanner scanner = new Scanner(System.in);
        while(true){
            if("exit".equalsIgnoreCase(scanner.nextLine())){
                break;
            }
        }
        distributeClient.closeConnection();
    }

    public void process(WatchedEvent watchedEvent) {
        if(Event.KeeperState.SyncConnected == watchedEvent.getState()){
            System.out.println("客户端链接成功");
            countDownLatch.countDown();
        }
        try {
            getServerList(); //链接成功的时候就注册监听
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void getServerList() throws KeeperException, InterruptedException {
        List<String> childrenList = zooKeeper.getChildren(PARRENT_NODE,true);
        List<String> allServerHost = new ArrayList<String>();
        for(String child : childrenList){
            byte[] hostByte = zooKeeper.getData(PARRENT_NODE + "/" +child,false,null);
            allServerHost.add(new String(hostByte));
        }
        serverList = allServerHost;
        System.out.println(serverList);
    }

    public void closeConnection() throws InterruptedException {
        if(zooKeeper != null){
            zooKeeper.close();
            System.out.println("客户端链接关闭");
        }
    }
}

客户端就可以动态的监听服务器变化。

客户端链接成功
[10.12.81.21]
客户端链接成功
[10.12.81.22, 10.12.81.21]
客户端链接成功
[10.12.81.22]
客户端链接成功
[]

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值