简体   繁体   中英

How to store a list of strings in a single ZooKeeper znode using Curator

For example, there is a znode path A/B/C/D . I'd like to store a list of Strings on that znode. Obviously, I could use join a list of strings into the single string and then serialize it into byte array like this:

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

But this looks not very convenient. Is there any other approach?

The easiest/best way to do it is probably to use ApacheUtils:

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

and to get it out:

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

This is a rather general aproach that will work with most java objects.

You may use Json serialization to store byte stream of list to node if that helps. I used jackson library for the same.

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();
}

Output:

[First, Second]

I hope this is also helpful to someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM