如何使用Curator在单个ZooKeeper znode中存储字符串列表

时间:2016-01-16 12:36:46

标签: java apache-zookeeper apache-curator

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

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

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

2 个答案:

答案 0 :(得分:3)

最简单/最好的方法可能是使用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对象。

答案 1 :(得分:2)

如果有帮助,您可以使用Json序列化将列表的字节流存储到节点。 我使用了杰克逊图书馆。

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]

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