java zookeeper 删除目录_zookeeper 节点的移动与删除

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

//获取节点下的一级子节点

List children = 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);

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值