例如,有一个 znode 路径A/B/C/D
。我想在那个 znode 上存储一个字符串列表。显然,我可以使用将字符串列表加入单个字符串,然后将其序列化为字节数组,如下所示:
curator.create()
.creatingParentContainersIfNeeded()
.forPath(path, value.getBytes(StandardCharsets.UTF_8));
但这看起来不是很方便。还有其他方法吗?
例如,有一个 znode 路径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);
这是一种适用于大多数 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]
我希望这对某人也有帮助。