@Slf4j
public class ZookeeperClientTest {
private static final String ZK_ADDRESS="192.168.109.200:2181";
private static final int SESSION_TIMEOUT = 5000;
private static ZooKeeper zooKeeper;
private static CountDownLatch countDownLatch=new CountDownLatch(1);
public static void main(String[] args){
zookeeper=new Zookeeper(ZK_ADDRESS,SESSION_TIMEOUT,new Watcher(){
@Override
public void process(WatchedEvent event){
if(event.getType()==Event.EventType.None&&
event.getState()==Event.KeeperState.SyncConnected){
log.info("链接已经建立");
countDownLatch.countDown();
}
});
countDownLatch.await();
MyConfig myConfig=new MyConfig();
myConfig.setKey("anyKey");
myConfig.setName("anyName");
ObjectMapper objectMapper=new ObjectMapper();
byte[] bytes =objectMapper.writeValueAsBytes(myConfig);
zookeeper.create("/myconfig",bytes,ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
Watcher watcher=new Watcher(){
@Override
public void process(WathedEvent event){
if(event.getType()==NodeDataChanged){
byte[]data=zookeeper.getData("/myConfig",this,null);
MyConfig newConfig=objectMapper.readValue(new String(data),MyConfig.class);
log.info("发生了数据变化,变化为:"+newConfig)
}
}
};
zookeeper.getData("/myConfig",watcher,null);
}
@Data
@ToString
@NoArgsConstructor
public class MyConfig{
private String key;
private String name;
}
|