Java 如何使用Curator在单个ZooKeeper znode中存储字符串列表
例如,有一个znode路径Java 如何使用Curator在单个ZooKeeper znode中存储字符串列表,java,apache-zookeeper,apache-curator,Java,Apache Zookeeper,Apache Curator,例如,有一个znode路径a/B/C/D。 我想在znode上存储字符串列表。 显然,我可以使用将字符串列表连接到单个字符串中,然后将其序列化到字节数组中,如下所示: curator.create() .creatingParentContainersIfNeeded() .forPath(path, value.getBytes(StandardCharsets.UTF_8)); 但这看起来不太方便。 还有其他方法吗?最简单/最好的方法可能是使
a/B/C/D
。
我想在znode上存储字符串列表。
显然,我可以使用将字符串列表连接到单个字符串中,然后将其序列化到字节数组中,如下所示:
curator.create()
.creatingParentContainersIfNeeded()
.forPath(path, value.getBytes(StandardCharsets.UTF_8));
但这看起来不太方便。
还有其他方法吗?最简单/最好的方法可能是使用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);
byte[]output=curator.getData().forPath(路径);
List newList=(List)SerializationUtils.deserialize(output);
这是一种相当通用的方法,适用于大多数java对象。如果有帮助,您可以使用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]