zookeeper_api使用

应用jar包 zookeeper-3.5.3-beta.jar以及zk目录的lib下面所有包

package com.download;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;

/**
 * @title: zookeeper api
 * @author: miracle
 * @date: 2018-01-09
 * @description: 提供了Naming类
 *
 */
public class Naming {
    private ZooKeeper zk = null; // zk对象
    private String nameRoot = "/NameService";
    private String nameRootValue = "isNameService";
    private String nameValue = "isName";

    /**
     * 构造函数
     * @param url zk的地址端口 初始化zk实例
     */
    public Naming(String url) {
        try {
            // 初始化,如果当前有alive的zk连接,则先关闭
            if (zk != null && zk.getState().isAlive()) {
                zk.close();
                zk = new ZooKeeper(url, 30000, null); // 重新建立连接
                System.out.println("ZooKeeper connect success; url=" + url);
            }
        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
        }

        try {
            // 判断是否有/NameService,如果没有,则创建该路径,用来作为所有的集中配置信息的根目录
            if (zk.exists(nameRoot, false) == null) {
                zk.create(nameRoot, nameRoot.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                System.out.println(nameRoot + " create success!");
            }
        } catch (InterruptedException | KeeperException e) {
            e.printStackTrace();
        }
    }

    /**
     * 注销zk实例
     */
    public void unNaming() {
        if (zk != null) {
            try {
                zk.close();
                System.out.println("ZooKeeper close success");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 注册一个全局名字
     * @param name 待注册的名字字符串
     * @return 0->表示注册成功 -1->表示出错 1->表示该命名已注册
     */
    public int registered(String name) {
        String path = nameRoot + "/" + name;
        int ret = 0;

        try {
            if (zk.exists(path, false) == null) {
                zk.create(path, path.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                System.out.println(name + " registered success");
            } else {
                ret = 1;
                System.out.println(name + " is exists, can not register again");
            }
        } catch (KeeperException | InterruptedException e) {
            ret = -1;
            e.printStackTrace();
        } 
        return ret;
    }

    /**
     * 注销一个全局名字
     * @param name 待注销的名字字符串
     * @return 0->表示注销成功 -1->表示出错 1->表示该命名未注册,不在命名服务系统中
     */
    public int canceled(String name) {
        String path = nameRoot + "/" + name;
        int ret = 0;

        try {
            if (zk.exists(path, false) == null) {
                zk.delete(name, -1); // -1表示匹配所有版本
                System.out.println(name + " canceled success");
            } else {
                ret = 1;
                System.out.println(name + " is exists, can not canceled");
            }
        } catch (KeeperException | InterruptedException e) {
            ret = -1;
            e.printStackTrace();
        } 
        return ret;
    }

    /**
     * 读取所有信息
     * @return
     */
    public List<String> readAll() {
        List<String> namelist = new ArrayList<String>();
        try {
            namelist = zk.getChildren(nameRoot, false);
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return namelist;
    }

    /**
     * testWatcher
     */
    public void testWatcher() {
        TestWatcher watcher = new TestWatcher(zk, nameRoot);
        Stat s = null;
        try {
            if ((s = zk.exists(nameRoot, watcher)) != null) {
                zk.setData(nameRoot, "10.0.0.0".getBytes(), s.getVersion());
            }
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    public class TestWatcher implements Watcher {

        private ZooKeeper zk;
        private String path;

        public TestWatcher(ZooKeeper zk, String path) {
            this.zk = zk;
            this.path = path;
        }

        @Override
        public void process(WatchedEvent event) {
            System.out.println("Path=" + event.getPath());
            System.out.println("KeeperState" + event.getState());
            System.out.println("EventType" + event.getType());

            try {
                zk.exists(path, this); // zk中一个watcher只能watch一次,之后需要重新watch
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void getAcl() {
        Stat s = null;
        try {
            if ((s = zk.exists(nameRoot, false)) != null) {
                List<ACL> acl = zk.getACL(nameRoot, s);
                for (ACL a : acl) {
                    System.out.println("id=" + a.getId());
                    System.out.println("perm=" + a.getPerms()); //perm返回的结果是十进制,acl是二进制1111=31
                }
            }
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取zk指定集群ip的集群状态
     * 通过srvr指令获取
     * @param hostStr
     * @param portStr
     * @return
     */
    public static String getServerState(String hostStr, String portStr) {
        final String host = hostStr;
        final int port = Integer.parseInt(portStr);
        final String cmd = "srvr";

        if (host.isEmpty() || host == null || port < 1024 || port > 65535) {
            return "";
        }
        Socket socket = null;
        OutputStream outputStream = null;
        BufferedReader reader = null;
        try {
            InetAddress inetAddress = InetAddress.getByName(host);
            socket = new Socket(inetAddress, port);
            socket.setSoTimeout(30000);
            outputStream = socket.getOutputStream();
            outputStream.write(cmd.getBytes());
            outputStream.flush();

            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值