目标:实现一个zookeeper系统的znode数据迁移到另一个zookeeper系统。
代码如下:MoveZkNode.java
import java.util.List;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
public class MoveZkNode {
public static void main(String[] args) throws Exception{
//旧zookeeper系统
ZooKeeper oldzk = new ZooKeeper("10.1.236.55:2181,10.1.236.56:2181,10.1.236.57:2181", 60000, null);
//新zookeeper系统
ZooKeeper newzk = new ZooKeeper("10.1.236.51:2181,10.1.236.58:2181,10.1.236.59:2181", 60000, null);
//需要迁移的znode
String node = "/hbase-unsecure";
List<String> children = oldzk.getChildren(node, false);
move(oldzk, newzk, children,node);
oldzk.close();
newzk.close();
}
public static void CreateZnode(ZooKeeper newzk,String str,String data ) {
String result = null;
try {
result = newzk.create(str, data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("创建znode:" + result);
}
private static void move(ZooKeeper oldzk, ZooKeeper newzk, List<String> children,String parent)
throws KeeperException, InterruptedException {
if(children==null || children.isEmpty()){
return;
}else{
if(newzk.exists(parent, false)==null){
CreateZnode(newzk,parent,"null");
}
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);
}else{
newzk.setData(c, data, -1, null, null);
}
move(oldzk, newzk, oldzk.getChildren(c, false),c);
}
}
}
}