java构建zk集群客户端

zookeeper版本jar

zkclient-0.8.jar

zookeeper-3.4.6.jar

属性文件properties

zookeeper.cluster=10.2.4.12\:2181,10.2.4.13\:2181,10.2.4.14\:2181

构建客户端

自己构建zk路径 根据实际情况修改 zk路径获取信息 DIR_SIGN+ROOT_NAME+DIR_SIGN+"ids"
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

/**
 * #zookeeper监控配置
   #zookeeper.cluster=10.2.4.12:2181,10.2.4.13:2181,10.2.4.14:2181
   #zookeeper.cluster=127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183
   #zookeeper.timeout=5000
 * ZkMonitor schedule
 */
public class ZkMonitor {
    private static String zk_cluster = "";
    private static int zk_timeout = 0;
    private static Timer timer = new Timer();
    private static ZkClient zk;
    public static final String ROOT_NAME = "brokers";
    public static final String DIR_SIGN = "/";
    public static String host_port = "";
    static {
        InputStream is = ZkMonitor.class.getResourceAsStream("/monconfig.properties");
        Properties props = new Properties();
        try {
            props.load(is);
            zk_cluster = props.getProperty("zookeeper.cluster");
            zk_timeout = Integer.parseInt(props.getProperty("zookeeper.timeout"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        //zk配置
        if(null == zk_cluster || "".equals(zk_cluster)){
            System.out.println("zookeeper.cluster is not config at monconfig.properties");
            if(0==zk_timeout){
                System.out.println("zookeeper.timeout is not config at monconfig.properties"); 
            }
        }else{
            try {
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        System.out.println(start());
                    }
                }, 5000, 5000);
            } catch (Exception e) {

            }
        }
    }

    
    public static boolean start() {
        try{
            zk = new ZkClient(zk_cluster,zk_timeout);
            List brokers = zk.getChildren(DIR_SIGN+ROOT_NAME+DIR_SIGN+"ids");
            if(null != brokers){
                for(int i = 0 ;i


你可能感兴趣的:([老达笔记]Zookeeper)