java操作zookeeper

依赖

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.8.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.zookeeper</groupId>
        <artifactId>zookeeper</artifactId>
        <version>3.4.10</version>
    </dependency>
</dependencies>

一些api的demo:

public class TestZookeeper {

    // 2181 : 访问 zookeeper集群的端口号
    private String connectString = "172.20.10.14:2181,172.20.10.4:2181,172.20.10.5:2181";
    private int sessionTimeout = 2000;
    private ZooKeeper zkClient;

    @Before
    public void init() throws IOException {
         zkClient = new ZooKeeper(connectString, 2000, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {

            }
        });
    }

    //创建节点
    @Test
    public void create() throws Exception {

        // 参数1:要创建的节点的路径;
        // 参数2:节点数据 ;
        // 参数3:节点权限 ;
        // 参数4:节点的类型
        String nodeCreated = zkClient.create("/atguigu", "jinlian".getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println(nodeCreated);
    }


    //创建子节点并监控数据的变化
    @Test
    public void getDataAndWatch() throws Exception {
        List<String> children = zkClient.getChildren("/", false);

        for (String s:children){
            System.out.println(s);
        }

    }

    // 判断znode是否存在
    @Test
    public void exist() throws Exception {

        Stat stat = zkClient.exists("/sanguo", false);

        System.out.println(stat == null ? "not exist" : "exist");
    }
}

【案例】服务器动态节点上下线

需求:

某分布式系统中,主节点可以有多台,可以动态上下线,任意一台客户端都能实时

感受到主服务器节点的上下线

过程:

clipboard

代码实现

服务器端:将自己的信息注册到zookeeper

public class DistributeServer {

    // 2181 : 访问 zookeeper集群的端口号
    private String connectString = "172.20.10.14:2181,172.20.10.4:2181,172.20.10.5:2181";
    private int sessionTimeout = 2000;
    private ZooKeeper zkClient;

    // 获取与zookeeper集群的连接
    private void getConnect() throws IOException {
        zkClient = new ZooKeeper(connectString, 2000, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {

            }
        });
    }


    private void regist(String hostName) throws Exception {
        String path = zkClient.create("/servers/server", hostName.getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(hostName + " is on line!");

    }

    private void business() throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE); //保证此进程不结束
    }

    public static void main(String[] args) throws Exception {

        //1.连接服务器集群
        DistributeServer server = new DistributeServer();
        server.getConnect();
        //2.注册节点
        server.regist(args[0]);

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

客户端:监听zookeeper某个节点下,子节点的变化信息

public class DistrubuteClient {

    // 2181 : 访问 zookeeper集群的端口号
    private String connectString = "172.20.10.14:2181,172.20.10.4:2181,172.20.10.5:2181";
    private int sessionTimeout = 2000;
    private ZooKeeper zkClient;

    // 获取与zookeeper集群的连接
    private void getConnect() throws IOException {
        zkClient = new ZooKeeper(connectString, 2000, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                try {
                    getChildren();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getChildren() throws Exception {
        List<String> children = zkClient.getChildren("/servers", true);
        //存储服务器节点主机名称的集合
        ArrayList<String> list = new ArrayList<>();
        for(String child:children){
            byte[] data = zkClient.getData("/servers/" + child, false, null);
            list.add(new String(data ));
        }
        //将所有主机名称在线打印
        System.out.println(list);
    }

    private void business() throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE); //保证此进程不结束
    }

    public static void main(String[] args) throws Exception {
        DistrubuteClient client =new DistrubuteClient();
        // 获取连接
        client.getConnect();
        //2.注册监听
        client.getChildren();

        client.business();
    }
}

这样客户端就能动态的监视服务端主机的变化情况

原文地址:https://www.cnblogs.com/houchen/p/13360511.html