用Java代码实现监控zookeeper节点信息的变化以及遍历节点

作者: admin 分类: Zookeeper 发布时间: 2019-01-03 23:32  阅读: 177 views

代码比较简单,附上待深剖

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

public class ZkService implements InitializingBean{
  private static final Logger logger = LoggerFactory.getLogger(ZkService.class);
  public static final String ZK_PATH_APP_AUTH = "/test";  
  private String zkUrl;
  private ZkClient zk;
  
  private IZkDataListener initDataListener() {
    IZkDataListener listener = new IZkDataListener() {
      @Override
      public void handleDataChange(String dataPath, Object data) throws Exception {
        String value = data.toString();
        logger.info(dataPath + "=" + value);
        if (StringUtils.isEmpty(value)) {
          return;
        }
        value = value.split("#")[0];
        if (StringUtils.isNumeric(value)) {
          if (ZK_PATH_API.equals(dataPath)) {
            /** TODO
             * 
             */
          }
        }
      }

      @Override
      public void handleDataDeleted(String dataPath) throws Exception {

      }

    };
    return listener;
  }
  
  private void init() throws Exception{
    
    zk = new ZkClient(zkUrl,10000,10000,new SerializableSerializer());  
        if(!zk.exists(ZK_PATH_APP_AUTH)){
      zk.createPersistent(ZK_PATH_APP_AUTH);
    }
    IZkDataListener listener = initDataListener();
    zk.subscribeDataChanges(ZK_PATH_APP_AUTH, listener);    
  }

  public String getZkUrl() {
    return zkUrl;
  }

  public void setZkUrl(String zkUrl) {
    this.zkUrl = zkUrl;
  }

  @Override
  public void afterPropertiesSet() throws Exception {
    init();
  }
}
public static void main(String[] args) {
 zk = new ZkClient(zkUrl,10000,10000,new SerializableSerializer());  
    String path = "/dubbo";
    output(0, path);
    
  }

  private static void output(int deep, String path) {
    //输出当前路径和数据
    System.out.println(getPrefix(deep)+path+"  "+JSON.toJSONString(zk.readData(path)));
    //查询子节点
    List<String> list = zk.getChildren(path);
    if(list == null || list.isEmpty()) {
      return;
    }
    //输出子节点
    for(String value : list) {
      output(deep+1, path+"/"+value);
    }
  }
  
  private static String getPrefix(int i) {
    String str = "----------------------------------------";
    return str.substring(0,i*2); //层级展示处理
  }

 


   原创文章,转载请标明本文链接: 用Java代码实现监控zookeeper节点信息的变化以及遍历节点

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

发表评论

电子邮件地址不会被公开。 必填项已用*标注