萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> MySQL 教學

ZooKeeper 跨集群數據遷移實戰:基於 Curator 的遞歸複製工具開發

ZooKeeper 作為分布式協調服務,其數據模型類似檔案系統。當需在不同集群間遷移節點數據(如誤刪恢復、測試環境導入線上數據)時,直接複製數據目錄不可行(二進位不可讀、無法選擇性遷移)。本文提供基於 Apache Curator 的 Java 遞歸複製完整實現。

應用場景

  1. 誤刪除生產集群某路徑數據,從備份集群恢復
  2. 新建測試環境,需從線上集群導入特定業務節點

核心思路

ZooKeeper 節點操作與檔案系統高度相似:

  • 遞歸遍歷源集群指定根路徑
  • 讀取每個節點的資料與子節點列表
  • 在目標集群按相同路徑創建持久節點並寫入資料

完整 Java 實現

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

ZkDao 工具類關鍵方法

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

關鍵設計點

  1. creatingParentsIfNeeded():自動創建中間路徑,無需手動遞歸建目錄
  2. PERSISTENT 模式:適合配置類數據;臨時節點需用 EPHEMERAL 但通常不跨集群遷移
  3. 錯誤處理:統一拋出業務異常,上層可決定重試或記錄失敗節點
  4. 冪等性:目標節點已存在時會拋 NodeExistsException,生產環境建議捕獲後更新資料或跳過

生產環境增強建議

  • 加入校驗和比對:遷移前後對比節點數、資料 MD5
  • 支援增量同步:對比版本號或修改時間,僅遷移變更節點
  • 並行化:大規模樹結構可用線程池並行處理不同分支
  • ACL 遷移:同步複製節點的 ACL 權限資訊
  • 監控與告警:記錄遷移耗時、成功率,異常即時通知

總結

利用 Curator 高階 API,ZooKeeper 跨集群數據遷移可實現為簡潔的遞歸邏輯。核心在於統一命名空間、自動創建父路徑、異常隔離。生產環境建議在工具基礎上增加校驗、增量、並行與監控能力,構建可靠的數據遷移管道。

copyright © 萬盛學電腦網 all rights reserved