zookeeper 使用 curator (参考druid.io源码)

创建节点

 static String path = "/test/task";

 public static void main(String[] args) {
      RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);
      CuratorFramework cf = CuratorFrameworkFactory.newClient("127.0.0.1:2181",
              5000,1000,retryPolicy);
      cf.start();
      try {
          CuratorUtils.createIfNotExists(cf,
                  path,
                  CreateMode.PERSISTENT,
                  StringUtils.toUtf8("hello"),
                  20);
      }
      catch (KeeperException.NodeExistsException e) {
          log.info("Skipping create path[%s], since it already exists.", path);
      }catch (Exception e){
          log.info("error create path[%s]", path);
      }
  }

在这里插入图片描述

  • CuratorUtils(来自druid.io 的源码)
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;

public class CuratorUtils {
    public static final int DEFAULT_MAX_ZNODE_BYTES = 512 * 1024;

    private static final Logger log = new Logger(CuratorUtils.class);

    /**
     * Create znode if it does not already exist. If it does already exist, this does nothing. In particular, the
     * existing znode may have a different payload or create mode.
     *
     * @param curatorFramework curator
     * @param path             path
     * @param mode             create mode
     * @param rawBytes         payload
     * @param maxZnodeBytes    maximum payload size
     *
     * @throws IllegalArgumentException if rawBytes.length > maxZnodeBytes
     * @throws Exception                if Curator throws an Exception
     */
    public static void createIfNotExists(
            CuratorFramework curatorFramework,
            String path,
            CreateMode mode,
            byte[] rawBytes,
            int maxZnodeBytes
    ) throws Exception
    {
        verifySize(path, rawBytes, maxZnodeBytes);

        if (curatorFramework.checkExists().forPath(path) == null) {
            try {
                curatorFramework.create()
                        .creatingParentsIfNeeded()
                        .withMode(mode)
                        .forPath(path, rawBytes);
            }
            catch (KeeperException.NodeExistsException e) {
                log.info("Skipping create path[%s], since it already exists.", path);
            }
        }
    }

    /**
     * Create znode if it does not already exist. If it does already exist, update the payload (but not the create mode).
     * If someone deletes the znode while we're trying to set it, just let it stay deleted.
     *
     * @param curatorFramework curator
     * @param path             path
     * @param mode             create mode
     * @param rawBytes         payload
     * @param maxZnodeBytes    maximum payload size
     *
     * @throws IllegalArgumentException if rawBytes.length > maxZnodeBytes
     * @throws Exception                if Curator throws an Exception
     */
    public static void createOrSet(
            CuratorFramework curatorFramework,
            String path,
            CreateMode mode,
            byte[] rawBytes,
            int maxZnodeBytes
    ) throws Exception
    {
        verifySize(path, rawBytes, maxZnodeBytes);

        boolean created = false;
        if (curatorFramework.checkExists().forPath(path) == null) {
            try {
                curatorFramework.create()
                        .creatingParentsIfNeeded()
                        .withMode(mode)
                        .forPath(path, rawBytes);

                created = true;
            }
            catch (KeeperException.NodeExistsException e) {
                log.debug("Path [%s] created while we were running, will setData instead.", path);
            }
        }

        if (!created) {
            try {
                curatorFramework.setData()
                        .forPath(path, rawBytes);
            }
            catch (KeeperException.NoNodeException e) {
                log.warn("Someone deleted path[%s] while we were trying to set it. Leaving it deleted.", path);
            }
        }
    }

    private static void verifySize(String path, byte[] rawBytes, int maxZnodeBytes)
    {
        if (rawBytes.length > maxZnodeBytes) {
            throw new IAE(
                    "Length of raw bytes for znode[%s] too large[%,d > %,d]",
                    path,
                    rawBytes.length,
                    maxZnodeBytes
            );
        }
    }
}

set / get 节点数据

RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);
     CuratorFramework cf = CuratorFrameworkFactory.newClient("127.0.0.1:2181",
             5000,1000,retryPolicy);
     cf.start();
     try {
         byte[] newData = StringUtils.toUtf8("hello_world");
         CuratorUtils.createOrSet(cf,
                 path,
                 CreateMode.PERSISTENT,
                 newData,
                 20);

         final byte[] bytes = cf.getData().forPath(path);
         String val = new String(bytes);
         System.out.println("get data from zkNode:" + val);
     }
     catch (KeeperException.NodeExistsException e) {
         log.info("Skipping create path[%s], since it already exists.", path);
     }catch (Exception e){
         log.info("error create path[%s]", path);
     }

监听节点

 RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);
 CuratorFramework cf = CuratorFrameworkFactory.newClient("127.0.0.1:2181",
         5000,1000,retryPolicy);
 cf.start();
 try {
     Stat stat = cf.checkExists().usingWatcher(
             (CuratorWatcher) watchedEvent -> {
                 switch (watchedEvent.getType()) {
                     case NodeDeleted:
                         break;
                     case NodeDataChanged:
                         System.out.println("NodeDataChanged:" + watchedEvent.getPath());
                         break;
                     default:
                         // do nothing
                 }
             }
     ).forPath(path);
     int dataLength = stat.getDataLength();
     System.out.println("dataLength:" + dataLength);
 }catch (Exception e){
     log.info("error", path);
 }

EPHEMERAL 节点

临时节点的生命周期和客户端会话绑定。如果客户端会话失效,那么这个节点就会自动被清除掉。注意,这里提到的是会话失效,而非连接断开;另外,在临时节点下面不能创建子节点

public static void main(String[] args) {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);
        CuratorFramework cf = CuratorFrameworkFactory.newClient("127.0.0.1:2181",
                5000,1000,retryPolicy);
        cf.start();
        try {
            byte[] newData = StringUtils.toUtf8("host1,host2");
            CuratorUtils.createIfNotExists(cf,
                    path,
                    CreateMode.EPHEMERAL,
                    newData,
                    20);

            final byte[] bytes = cf.getData().forPath(path);
            String val = new String(bytes);
            System.out.println("get data from zkNode:" + val);
        }
        catch (KeeperException.NodeExistsException e) {
            log.info("Skipping create path[%s], since it already exists.", path);
        }catch (Exception e){
            log.info("error create path[%s]", path);
        }
        try {
            TimeUnit.SECONDS.sleep(20);
        }catch (Exception e){

        }
        cf.close();
    }

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值