package com.zhengmo.test;import java.util.List;import org.apache.zookeeper.CreateMode;import org.apache.zookeeper.KeeperException;import org.apache.zookeeper.ZooDefs.Ids;import org.apache.zookeeper.ZooKeeper;/** * @author zhengmo */public class ZkMove { private static int deleteCount = 0; private static int moveCount = 0; public static void main(String[] args) throws Exception { // //旧zk服务器 ZooKeeper oldzk = new ZooKeeper("192.168.1.112:2181", 60000, null); //新zk服务器 ZooKeeper newzk = new ZooKeeper("172.17.32.105:2181", 60000, null); //需要迁移的节点 String node = "/dubbo"; //删除指定节点 delete(newzk, node); System.out.println("删除节点数:" + deleteCount); //获取节点下的一级子节点 Listchildren = oldzk.getChildren(node, false); move(oldzk, newzk, children, node); System.out.println("移动节点数:" + moveCount); oldzk.close(); newzk.close(); } /** * 递归删除指定节点的子节点. * @param newzk zk * @param node 节点 * @return 成功否 * @throws Exception 异常 */ private static boolean delete(ZooKeeper newzk, String node) throws Exception { List children = newzk.getChildren(node, false); if (children == null || children.size() == 0) { //System.out.println("delete node:" + node); newzk.delete(node, -1); deleteCount++; return true; } else { for (String child : children) { while (!delete(newzk, node + "/" + child)) { } } return false; } } /** * 移动指定zk1的指定节点到指定zk2的节点下. * @param oldzk 旧zk * @param newzk 新zk * @param children 子节点 * @param parent 父节点 * @throws KeeperException 异常 * @throws InterruptedException 异常 */ private static void move(ZooKeeper oldzk, ZooKeeper newzk, List children, String parent) throws KeeperException, InterruptedException { if (newzk.exists(parent, false) == null) { newzk.create(parent, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); System.out.println("create " + parent); } if (children == null || children.isEmpty()) { return; } else { for (String child : children) { String c = parent + "/" + child; //System.out.println(c); byte[] data = oldzk.getData(c, false, null); if (newzk.exists(c, false) == null) { newzk.create(c, data, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); moveCount++; } else { newzk.setData(c, data, -1, null, null); moveCount++; } //递归移动 move(oldzk, newzk, oldzk.getChildren(c, false), c); } } }}
zookeeper 有时候需要移动节点。
posted on 2016-01-07 10:40 阅读( ...) 评论( ...)