ZooKeeper 作為分布式協調服務,其數據模型類似檔案系統。當需在不同集群間遷移節點數據(如誤刪恢復、測試環境導入線上數據)時,直接複製數據目錄不可行(二進位不可讀、無法選擇性遷移)。本文提供基於 Apache Curator 的 Java 遞歸複製完整實現。
ZooKeeper 節點操作與檔案系統高度相似:
import com.netflix.curator.framework.CuratorFramework;
import com.netflix.curator.framework.CuratorFrameworkFactory;
import com.netflix.curator.retry.RetryNTimes;
import java.util.List;
public class ZookeeperClusterCopy {
private static CuratorFramework clientSrc;
private static CuratorFramework clientDst;
private static final String ZK_ROOT_SRC = "/app";
public static void main(String[] args) throws Exception {
// 源集群連接字串
String srcConnStr = "10.0.0.1:2181,10.0.0.2:2181,10.0.0.3:2181";
clientSrc = buildClient(srcConnStr, null, 60000);
// 目標集群連接字串
String dstConnStr = "10.0.1.1:2181,10.0.1.2:2181,10.0.1.3:2181";
clientDst = buildClient(dstConnStr, null, 60000);
copyDataRecursion(ZK_ROOT_SRC);
System.out.println("跨集群數據遷移完成");
}
/** 遞歸複製節點及其子樹 */
private static void copyDataRecursion(String parentPath) throws Exception {
List children = ZkDao.getChildren(clientSrc, parentPath);
if (children.isEmpty()) {
// 葉子節點:直接複製資料
byte[] data = ZkDao.getData(clientSrc, parentPath);
ZkDao.createPersistent(clientDst, parentPath, data);
System.out.println("Copied leaf: " + parentPath);
return;
}
// 先確保父節點存在(含資料)
byte[] parentData = ZkDao.getData(clientSrc, parentPath);
ZkDao.createPersistent(clientDst, parentPath, parentData);
for (String child : children) {
String childPath = parentPath + "/" + child;
copyDataRecursion(childPath);
}
}
/** 建立 Curator 客戶端 */
private static CuratorFramework buildClient(String connStr, String namespace, int sessionTimeoutMs) throws Exception {
return CuratorFrameworkFactory.builder()
.connectString(connStr)
.retryPolicy(new RetryNTimes(3, 10000))
.connectionTimeoutMs(60000)
.sessionTimeoutMs(sessionTimeoutMs)
.namespace(namespace)
.build();
}
}
public class ZkDao {
/** 獲取節點資料 */
public static byte[] getData(CuratorFramework client, String path) {
try {
return client.getData().forPath(path);
} catch (Exception e) {
throw new ZkException("GET_DATA_FAILED", "path:" + path, e);
}
}
/** 獲取子節點列表 */
public static List getChildren(CuratorFramework client, String path) {
try {
return client.getChildren().forPath(path);
} catch (Exception e) {
throw new ZkException("GET_CHILDREN_FAILED", "path:" + path, e);
}
}
/** 創建持久節點(自動創建父路徑) */
public static void createPersistent(CuratorFramework client, String path, byte[] data) {
try {
client.create()
.creatingParentsIfNeeded()
.withMode(CreateMode.PERSISTENT)
.forPath(path, data);
} catch (Exception e) {
throw new ZkException("CREATE_FAILED", "path:" + path, e);
}
}
}
EPHEMERAL 但通常不跨集群遷移NodeExistsException,生產環境建議捕獲後更新資料或跳過利用 Curator 高階 API,ZooKeeper 跨集群數據遷移可實現為簡潔的遞歸邏輯。核心在於統一命名空間、自動創建父路徑、異常隔離。生產環境建議在工具基礎上增加校驗、增量、並行與監控能力,構建可靠的數據遷移管道。