zookeeper-3:使用zk实现分布式配置中心

1、在zookeeper里增加一个目录节点,并且把配置信息存储在里面

[zk: localhost:2181(CONNECTED) 8] create /username fengfeng
Created /username

2、启动两个zookeeper客户端程序,代码如下所示

import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
 
/**
 * 分布式配置中心demo
 * @author 
 *
 */
public class ZooKeeperProSync implements Watcher {
 
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
    private static ZooKeeper zk = null;
    private static Stat stat = new Stat();
 
    public static void main(String[] args) throws Exception {
        //zookeeper配置数据存放路径
        String path = "/username";
        //连接zookeeper并且注册一个默认的监听器
        zk = new ZooKeeper("192.168.31.100:2181", 5000, //
                new ZooKeeperProSync());
        //等待zk连接成功的通知
        connectedSemaphore.await();
        //获取path目录节点的配置数据,并注册默认的监听器
        System.out.println(new String(zk.getData(path, true, stat)));
 
        Thread.sleep(Integer.MAX_VALUE);
    }
 
    public void process(WatchedEvent event) {
        if (KeeperState.SyncConnected == event.getState()) {  //zk连接成功通知事件
            if (EventType.None == event.getType() && null == event.getPath()) {
                connectedSemaphore.countDown();
            } else if (event.getType() == EventType.NodeDataChanged) {  //zk目录节点数据变化通知事件
                try {
                    System.out.println("配置已修改,新值为:" + new String(zk.getData(event.getPath(), true, stat)));
                } catch (Exception e) {
                }
            }
        }
    }
}

两个程序启动后都正确的读取到了zookeeper的/username目录节点下的数据'fengfeng'
3、我们在zookeeper里修改下目录节点/username下的数据

[zk: localhost:2181(CONNECTED) 9] set /username qiqi

修改完成后,我们看见两个程序后台都及时收到了他们监听的目录节点数据变更后的值,如下所示

fengfeng
配置已修改,新值为:qiqi
``

你可能感兴趣的:(zookeeper-3:使用zk实现分布式配置中心)