zookeeper节点操作zkclient

我不是女神ヾ 2022-05-14 07:26 338阅读 0赞

增加、删除节点,监测节点信息的变化,解析json

  1. package com.keixn.inspect.controller;
  2. /**
  3. * @Author KeXin
  4. * @Date 2018/7/19 下午3:36
  5. **/
  6. import com.alibaba.fastjson.JSON;
  7. import com.alibaba.fastjson.JSONObject;
  8. import com.alibaba.fastjson.parser.ParserConfig;
  9. import org.I0Itec.zkclient.IZkDataListener;
  10. import org.I0Itec.zkclient.ZkClient;
  11. public class Get_Data_Sample {
  12. public static void main(String[] args) throws Exception {
  13. String path = "/zk-book";
  14. ZkClient zkClient = new ZkClient("localhost:2181", 5000);
  15. String d = "{\"@type\":\"com.alibaba.otter.canal.protocol.position.LogPosition\",\"identity\":{\"slaveId\":-1,\"sourceAddress\":{\"address\":\"192.168.13.90\",\"port\":8306}},\"postion\":{\"included\":false,\"journalName\":\"shrekdb.001783\",\"position\":649840868,\"serverId\":16815,\"timestamp\":1531982550000}}";
  16. zkClient.createEphemeral(path, d);
  17. zkClient.subscribeDataChanges(path, new IZkDataListener() {
  18. public void handleDataDeleted(String dataPath) throws Exception {
  19. System.out.println("Node " + dataPath + " deleted.");
  20. }
  21. public void handleDataChange(String dataPath, Object data) throws Exception {
  22. System.out.println("Node " + dataPath + " changed, new data: " + data);
  23. }
  24. });
  25. //读取节点数据
  26. String data = zkClient.readData(path);
  27. ParserConfig.getGlobalInstance().setAutoTypeSupport(true); //解决@type造成的bug,fastjson本身的原因
  28. JSONObject jsonObject = JSON.parseObject(data);
  29. long timestamp = Long.parseLong(jsonObject.getJSONObject("postion").get("timestamp").toString());
  30. long currentTime = System.currentTimeMillis();
  31. long diff = (currentTime-timestamp)/1000;
  32. System.out.println("-------------------------------------");
  33. System.out.println(timestamp);
  34. System.out.println(currentTime);
  35. System.out.println(diff);
  36. Thread.sleep(1000);
  37. zkClient.delete(path);
  38. Thread.sleep( Integer.MAX_VALUE );
  39. }
  40. }

发表评论

表情:
评论列表 (有 0 条评论,338人围观)

还没有评论,来说两句吧...

相关阅读