zookeeper创建客户端及操作(代码)

  • 创建一个 Maven 工程
  • 为 pom.xml 添加关键依赖
    <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>
        <!-- zookeeper -->
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.10</version>
        </dependency>
    </dependencies>
依赖

 

  • 需要在项目的 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
日志配置
 
 
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import javax.sound.midi.Soundbank;
import java.io.IOException;
import java.util.List;

public class TestZookeeper {
    //连接的zk集群
    private String connectString = "192.168.199.123:2181,192.168.199.124:2181";
    //设置连接超时时间
    private int sessionTimeout = 2000;
    private ZooKeeper zkClient;


    @Test
    public void init() throws IOException {
        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            //process会在init中先运行一遍,之后有其他将监听设为true时,会调用process方法
            public void process(WatchedEvent watchedEvent) {

            }
        });
    }
}
测试连接
 

创建节点,获取子节点并监控节点的变化,判断节点是否存在

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.List;

public class TestZookeeper {
    //连接的zk集群
    private String connectString = "192.168.199.123:2181,192.168.199.124:2181";
    //设置连接超时时间
    private int sessionTimeout = 2000;
    private ZooKeeper zkClient;


    //在Test之前执行,不然会报错
    @Before
    public void init() throws IOException {
        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            //process会在init中先运行一遍,之后有其他将监听设为true时,会调用process方法
            public void process(WatchedEvent watchedEvent) {
                List<String> children = null;
                try {
                    children = zkClient.getChildren("/", true);
                    for(String i :children){
                        System.out.println(i);
                    }
                    System.out.println("------------");
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //创建节点
    @Test
    public void createNode() throws KeeperException, InterruptedException {
        //参数:节点名,节点中的值,访问权限(只读什么的),节点类型(持久的,短暂的,带序号的)
        String path = zkClient.create("/sichuan", "chengdu".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println(path);
    }

    //获取子节点并监控节点的变化
    @Test
    public void getDataAndWatch() throws KeeperException, InterruptedException {
        //参数:需要获取子节点的路径,是否监听
        //监听的过程需要在init方法中的process中修改
        List<String> children = zkClient.getChildren("/", true);
        for(String i :children){
            System.out.println(i);
        }
        Thread.sleep(Long.MAX_VALUE);
    }

    // 判断节点是否存在
    @Test
    public void exist() throws Exception {
        Stat stat = zkClient.exists("/sichuan", false);
        System.out.println(stat == null ? "not exist" : "exist");
    }
}
总代码

 

服务器节点动态上下线

import org.apache.zookeeper.*;
import java.io.IOException;

//服务器与zk集群连接
public class DistributeServer {
    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        DistributeServer server = new DistributeServer();
        //连接zk集群
        server.getConnet();
        //注册监听
        server.regist(args[0]);
        //业务逻辑
        server.business();
    }

    private void regist(String hostname) throws KeeperException, InterruptedException {
        //参数:节点名,
        String path = zkClient.create("/servers/server", hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(hostname+" is online");
    }
    
    private void business() throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE);
    }
    
    //连接的zk集群
    private String connectString = "192.168.199.123:2181,192.168.199.124:2181";
    //设置连接超时时间
    private int sessionTimeout = 2000;
    private ZooKeeper zkClient;

    private void getConnet() throws IOException {

        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            public void process(WatchedEvent watchedEvent) {

            }
        });
    }
}
服务器DistributeServer
import org.apache.zookeeper.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

//客户端与zk集群连接
public class DistributeClient {
    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        DistributeClient client = new DistributeClient();
        //连接zk集群
        client.getConnet();
        //注册节点
        client.getChildren();
        //业务逻辑
        client.business();
    }

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

    private void getChildren() throws KeeperException, InterruptedException {
        //获取子节点名称并监听
        List<String> children = zkClient.getChildren("/servers", true);
        //存储服务器节点主机名称集合
        ArrayList<String> hosts = new ArrayList<String>();
        for (String i : children){
            byte[] data = zkClient.getData("/servers/" + i, false, null);
            hosts.add(new String(data));
        }
        //将所有在线主机名称打印到控制台
        System.out.println(hosts);
    }

    //连接的zk集群
    private String connectString = "192.168.199.123:2181,192.168.199.124:2181";
    //设置连接超时时间
    private int sessionTimeout = 2000;
    private ZooKeeper zkClient;

    private void getConnet() throws IOException {

        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            //监听内容
            public void process(WatchedEvent watchedEvent) {
                try {
                    getChildren();
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
客户端DistributeClient

 

posted @ 2021-08-22 14:48  低调的。。。  阅读(111)  评论(0编辑  收藏  举报