【问题标题】:How to store a list of strings in a single ZooKeeper znode using Curator如何使用 Curator 在单个 ZooKeeper znode 中存储字符串列表
【发布时间】:2016-09-29 15:00:46
【问题描述】:

例如有一个znode路径A/B/C/D。 我想在那个 znode 上存储一个字符串列表。 显然,我可以使用将字符串列表加入单个字符串,然后将其序列化为字节数组,如下所示:

curator.create()
            .creatingParentContainersIfNeeded()
            .forPath(path, value.getBytes(StandardCharsets.UTF_8));

但这看起来不太方便。 还有其他方法吗?

【问题讨论】:

    标签: java apache-zookeeper apache-curator


    【解决方案1】:

    最简单/最好的方法可能是使用 ApacheUtils:

    byte[] input = SerializationUtils.serialize(yourList);
    curator.create()
            .creatingParentContainersIfNeeded()
            .forPath(path, input);
    

    然后把它拿出来:

    byte[] output = curator.getData().forPath(path);
    List<String> newList = (List<String>)SerializationUtils.deserialize(output);
    

    这是一种相当通用的方法,适用于大多数 java 对象。

    【讨论】:

    • 谢谢,很好的解决方案!
    【解决方案2】:

    如果有帮助,您可以使用 Json 序列化将列表的字节流存储到节点。 我也使用了 jackson 库。

    ObjectMapper mapper = new ObjectMapper();
    List<String> inputList = Arrays.asList("First", "Second");
    try
    {
        byte[] writeValueAsBytes = mapper.writeValueAsBytes(inputList);
        curatorFramework.setData().forPath(zPath, writeValueAsBytes);
        byte[] outputBytes = curatorFramework.getData().forPath(zPath);
        List<String> outputList = mapper.readValue(outputBytes, ArrayList.class);
        System.out.println(outputList);
    } catch (Exception exception)
    {
        exception.printStackTrace();
    }
    

    输出:

    [First, Second]
    

    我希望这对某人也有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多