zookeeper api应用:
1.创建一个maven项目,pom引入依赖:
	<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>
        <!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper -->
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.10</version>
        </dependency>
    </dependencies>
拷贝log4j.properties文件到项目根目录

需要在项目的src/main/resources目录下,新建一个文件,命名为“log4j.properties”,在文件中填入

log4j.rootLogger=INFO, stdout  
log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n  
log4j.appender.logfile=org.apache.log4j.FileAppender  
log4j.appender.logfile.File=target/spring.log  
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout  
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n  
创建测试类,定义基本属性:
public class TestZookeeper {

    private String connectString = "127.0.0.1:2181";
    private int sessionTimeout = 2000;
    private ZooKeeper zooKeeper;
}
创建客户端:
    @Before
    public void init () throws IOException {
        zooKeeper =new ZooKeeper(connectString, sessionTimeout, new Watcher() {
        	// 收到事件通知后的回调函数(用户的业务逻辑)
            public void process(WatchedEvent watchedEvent) {
            }
        });
    }
创建子节点
    @Test
    public void creat () throws KeeperException, InterruptedException {
        String s = zooKeeper.create("/servers", "qwq".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println(s);
    }
获取子节点并监听节点变化
    // 获取子节点并监控节点的变化
    @Test
    public void getDataAndWatch () throws KeeperException, InterruptedException {
        List<String> children = zooKeeper.getChildren("/", false);
        for (String child : children) {
            System.out.println(child);
        }
    }
判断Znode是否存在
    @Test
    public void exists () throws KeeperException, InterruptedException {
        Stat exists = zooKeeper.exists("/servers", false);
        System.out.println(exists==null ? "not exists":"exists");
    }
基于api 实现监听服务器动态上下线:

对于zookeeper来说,服务器与客户端都是客户端,所以都需要注册
服务端:

package com.jym.zookeeper;

import org.apache.zookeeper.*;

import java.io.IOException;

/**
 * @program: zookeeperStud
 * @description:
 * @author: jym
 * @create: 2020/03/05
 */
public class DistributeServer {
    public static void main(String[] args) throws Exception {
        DistributeServer server = new DistributeServer();
        // 连接zookeeper
        server.getConnect();
        // 注册节点
        server.regist(args[0]);
        // 业务代码
        server.business();
    }

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

    private void regist (String data) throws KeeperException, InterruptedException {
        zooKeeper.create("/servers/server",data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
    }

    private String connectString = "127.0.0.1:2181";
    private int sessionTimeout = 2000;
    private ZooKeeper zooKeeper;

    private void getConnect () throws IOException {
        zooKeeper =new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            public void process(WatchedEvent watchedEvent) {
            }
        });
    }
}

客户端:

package com.jym.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.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: zookeeperStud
 * @description:
 * @author: jym
 * @create: 2020/03/05
 */
public class DistributeClient {
    public static void main(String[] args) throws Exception {
        DistributeClient client = new DistributeClient();
        client.getConnect();
        client.getChildren();
        client.business();
    }

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

    public void getChildren () throws KeeperException, InterruptedException {
        List<String> children = zooKeeper.getChildren("/servers", true);
        // 存储服务器主机名称集合
        Map<String,String> hosts = new HashMap<>();
        for (String child : children) {
            byte[] data = zooKeeper.getData("/servers/" + child, false, null);
            hosts.put(child,new String(data, Charset.forName("utf-8")));
        }
        System.out.println(hosts);
    }

    private String connectString = "127.0.0.1:2181";
    private int sessionTimeout = 2000;
    private ZooKeeper zooKeeper;

    private void getConnect () throws IOException {
        zooKeeper =new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            public void process(WatchedEvent watchedEvent) {
                try {
                    System.out.println("=========================");
                    getChildren();
                    System.out.println("=========================");
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
学习年限不足,知识过浅,说的不对请见谅。

世界上有10种人,一种是懂二进制的,一种是不懂二进制的。

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐