1. 程式人生 > >zookeeper節點操作zkclient

zookeeper節點操作zkclient

增加、刪除節點,監測節點資訊的變化,解析json

package com.keixn.inspect.controller;

/**
 * @Author KeXin
 * @Date 2018/7/19 下午3:36
 **/

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.ParserConfig;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient
.ZkClient; public class Get_Data_Sample { public static void main(String[] args) throws Exception { String path = "/zk-book"; ZkClient zkClient = new ZkClient("localhost:2181", 5000); 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}}"
; zkClient.createEphemeral(path, d); zkClient.subscribeDataChanges(path, new IZkDataListener() { public void handleDataDeleted(String dataPath) throws Exception { System.out.println("Node " + dataPath + " deleted."); } public void handleDataChange(String dataPath, Object data) throws Exception { System.out
.println("Node " + dataPath + " changed, new data: " + data); } }); //讀取節點資料 String data = zkClient.readData(path); ParserConfig.getGlobalInstance().setAutoTypeSupport(true); //解決@type造成的bug,fastjson本身的原因 JSONObject jsonObject = JSON.parseObject(data); long timestamp = Long.parseLong(jsonObject.getJSONObject("postion").get("timestamp").toString()); long currentTime = System.currentTimeMillis(); long diff = (currentTime-timestamp)/1000; System.out.println("-------------------------------------"); System.out.println(timestamp); System.out.println(currentTime); System.out.println(diff); Thread.sleep(1000); zkClient.delete(path); Thread.sleep( Integer.MAX_VALUE ); } }