增加、删除节点,监测节点信息的变化,解析json
package com.keixn.inspect.controller
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)
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 )
}
}