1.导入依赖
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>0.11</version>
</dependency>
测试类
class DemoApplicationTests {
@Test
void contextLoads() throws IOException {
//zookeeper地址,链接超时时间(毫秒),会话超时时间(毫秒),序列号
ZkClient ZkClient = new ZkClient("ip:2181,ip:2182,ip:2183",1000,10000,new CustomerSerializer());
//创建
//ZkClient.create("/mo46a","a123", CreateMode.PERSISTENT);
//修改
//ZkClient.writeData("/mo46a","123");
//查询
//Object readData = ZkClient.readData("/mo46a");
//System.out.println(readData);
//删除
//ZkClient.delete("/mo46a");
//监听
ZkClient.subscribeDataChanges("/mo46a", new IZkDataListener() {
//修改监听
@Override
public void handleDataChange(String s, Object o) throws Exception {
System.out.println("修改的:"+s+"修改后的"+o);
}
//删除监听
@Override
public void handleDataDeleted(String s) throws Exception {
System.out.println("删除的:"+s);
}
});
//监听父节点下的所有子节点
ZkClient.subscribeChildChanges("/mo46a", new IZkChildListener() {
@Override
public void handleChildChange(String s, List<String> list) throws Exception {
}
});
System.out.println(1);
System.in.read();
}
}
CustomerSerializer类
import org.I0Itec.zkclient.exception.ZkMarshallingError;
import org.I0Itec.zkclient.serialize.ZkSerializer;
import java.io.UnsupportedEncodingException;
public class CustomerSerializer implements ZkSerializer {
private String charset="UTF-8";
public CustomerSerializer() {
}
public CustomerSerializer(String charset) {
this.charset = charset;
}
//序列号
@Override
public byte[] serialize(Object o) throws ZkMarshallingError {
byte[] bytes=null;
try {
bytes=String.valueOf(o).getBytes(charset);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return bytes;
}
//反序列化
@Override
public Object deserialize(byte[] bytes) throws ZkMarshallingError {
String result=null;
try {
result=new String(bytes,charset);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
}