Zookeeper代码开发API

参照尚硅谷课程Zookeeper相关文档写出,做增强记忆之用。

基本操作

  1. 创建一个maven项目

  2. 导入依赖

    		<!-- 测试 -->
            <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.14</version>
            </dependency>
    
  3. 拷贝 log4j.properties 文件到 src/main/resources下,文件内容为

    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
    
  4. 创建连接的客户端对象

    public class TestZookeeper {
    
    	//集群地址,通过逗号隔开,不能加空格
        private String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
        //连接时的超时时间
        private int sessionTimeout = 2000;
        //客户端对象
        private ZooKeeper zkClient;
    
        @Before
        public void init() throws IOException {
            zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            	//观察者
                @Override
                public void process(WatchedEvent watchedEvent) {
                	//观察者代码
                }
            });
        }
    }
    
  5. 创建节点

    	//1. 创建节点
        @Test
        public void createNode() throws KeeperException, InterruptedException {
            String path = zkClient.create("/hxy", "helloAPI".getBytes(), 
            									ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            System.out.println(path);
        }
    
  6. 获取子节点并监控数据的变化

    	//2. 获取子节点并监控数据的变化
    	@Test
        public void getDataAndWatch() throws InterruptedException {
        	//try-catch的内容要在Watcher的process内也有一份,才能监听到
            try {
                List<String> children = zkClient.getChildren("/", true);
                for (String child : children) {
                    System.out.println(child);
                }
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            
            Thread.sleep(Long.MAX_VALUE);
        }
    
  7. 判断 Znode 是否存在

    	//3. 判断节点是否存在
        @Test
        public void exist() throws KeeperException, InterruptedException {
    
            Stat stat = zkClient.exists("/hxy", false);
    
            System.out.println(stat == null ? "no exist" : "exist");
        }
    

服务器动态上下线案例

  1. 服务器

    public class DistributeServer {
    
       private String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
       private int sessionTimeout = 2000;
       private ZooKeeper zkClient;
    
       public static void main(String[] args) throws Exception {
    
           DistributeServer server = new DistributeServer();
           //1.连接客户端
           server.getConnect();
           //2.注册节点,通过配置参数传递进来主机名称
           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 {
           String path = zkClient.create("/servers/server", hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
           System.out.println(hostname + "is online");
       }
    
       public void getConnect() throws IOException {
           zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
               @Override
               public void process(WatchedEvent watchedEvent) {
    
               }
           });
       }
    }
    
  2. 客户端

    public class DistributeClient {
    
        private String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
        private int sessionTimeout = 2000;
        private ZooKeeper zkClient;
    
        public static void main(String[] args) throws Exception {
            DistributeClient client = new DistributeClient();
            // 1.获取zookeeper集群的练级
            client.getConnect();
            // 2.获取节点
            client.getChildren();
            // 3. 业务逻辑
            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<>();
            for (String child : children) {
                byte[] data = zkClient.getData("/servers/" + child, false, null);
                hosts.add(new String(data));
            }
    
            System.out.println(hosts);
    
        }
    
        private void getConnect() throws IOException {
            zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    try {
                        getChildren();
                    } catch (KeeperException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值