ZooKeeper客户端ZKClient使用

准备

 在zookeeper所需jar包基础上,classpath加上zkclient-2.1.1.jar

代码示例

package zk_client;

import java.util.List;

import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.github.zkclient.IZkChildListener;
import com.github.zkclient.IZkDataListener;
import com.github.zkclient.IZkStateListener;
import com.github.zkclient.ZkClient;

public class ZKClientDemo
{
    private static final Logger log = LoggerFactory.getLogger(ZKClientDemo.class);
    
    public static void main(String[] args) throws InterruptedException
    {
        String path = "/zk_client_test";
        String c1Path = path + "/c1";
        String c2Path = path + "/c2";
        // 创建连接接口从原生的异步变成了同步
        ZkClient zkClient = new ZkClient("127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183", 3000);
        
        // 监听
        // IZkStateListener 定义了两种事件,一种是连接状态的改变,例如由未连接改变成连接上,连接上改为过期等;
        // 另一种创建一个新的session(连接), 通常是由于session失效然后新的session被建立时触发。一般此时需要开发者重新创建临时节点(Ephemeral Nodes)
        zkClient.subscribeStateChanges(new IZkStateListener()
        {
            @Override
            public void handleStateChanged(KeeperState state) throws Exception
            {
                log.info("handleStateChanged: " + state);
            }
            
            @Override
            public void handleNewSession() throws Exception
            {
                log.info("handleNewSession");
            }
        });
        
        zkClient.subscribeDataChanges(path, new IZkDataListener()
        {
            @Override
            public void handleDataDeleted(String path) throws Exception
            {
                log.info("delete node: " + path);
            }
            
            @Override
            public void handleDataChange(String path, byte[] data) throws Exception
            {
                log.info("node [{}] date changed: {}", path, data);
            }
        });
        
        // 节点变化了,这时候获取到的是新的子节点列表。如果此节点被删除,那么子节点列表是null
        zkClient.subscribeChildChanges(path, new IZkChildListener()
        {
            @Override
            public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception
            {
                log.info(parentPath + " 's child changed, currentChilds:" + currentChilds);
            }
        });
        
        // 直接创建多层节点
        zkClient.createPersistent(c1Path, true);
        zkClient.createPersistent(c2Path, true);
        Thread.sleep(2000);
        log.info(path + "exists? {}", zkClient.exists(path));
        
        // 更新数据
        zkClient.writeData(c2Path, "c2".getBytes());
        zkClient.writeData(path, "f".getBytes());
        
        // 读数据
        log.info("read path [{}], data: {}", path, new String(zkClient.readData(path)));
        // 如果为空返回null,不加这个参数默认抛出异常NoNode for /zk_client_test/c1/c
        log.info("read path [{}], data: {}", c1Path+"/c", zkClient.readData(c1Path+"/c", true));
        log.info("read path [{}], data: {}", c1Path, zkClient.readData(c1Path));
        log.info("read path [{}], data: {}", c2Path, new String(zkClient.readData(c2Path)));
        // 直接删除父节点,不用先删除子节点了
        Thread.sleep(2000);
        zkClient.deleteRecursive(path);
    }
}


你可能感兴趣的:(ZooKeeper客户端ZKClient使用)