应用jar包 zookeeper-3.5.3-beta.jar以及zk目录的lib下面所有包
package com.download;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
/**
* @title: zookeeper api
* @author: miracle
* @date: 2018-01-09
* @description: 提供了Naming类
*
*/
public class Naming {
private ZooKeeper zk = null; // zk对象
private String nameRoot = "/NameService";
private String nameRootValue = "isNameService";
private String nameValue = "isName";
/**
* 构造函数
* @param url zk的地址端口 初始化zk实例
*/
public Naming(String url) {
try {
// 初始化,如果当前有alive的zk连接,则先关闭
if (zk != null && zk.getState().isAlive()) {
zk.close();
zk = new ZooKeeper(url, 30000, null); // 重新建立连接
System.out.println("ZooKeeper connect success; url=" + url);
}
} catch (InterruptedException | IOException e) {
e.printStackTrace();
}
try {
// 判断是否有/NameService,如果没有,则创建该路径,用来作为所有的集中配置信息的根目录
if (zk.exists(nameRoot, false) == null) {
zk.create(nameRoot, nameRoot.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println(nameRoot + " create success!");
}
} catch (InterruptedException | KeeperException e) {
e.printStackTrace();
}
}
/**
* 注销zk实例
*/
public void unNaming() {
if (zk != null) {
try {
zk.close();
System.out.println("ZooKeeper close success");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 注册一个全局名字
* @param name 待注册的名字字符串
* @return 0->表示注册成功 -1->表示出错 1->表示该命名已注册
*/
public int registered(String name) {
String path = nameRoot + "/" + name;
int ret = 0;
try {
if (zk.exists(path, false) == null) {
zk.create(path, path.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println(name + " registered success");
} else {
ret = 1;
System.out.println(name + " is exists, can not register again");
}
} catch (KeeperException | InterruptedException e) {
ret = -1;
e.printStackTrace();
}
return ret;
}
/**
* 注销一个全局名字
* @param name 待注销的名字字符串
* @return 0->表示注销成功 -1->表示出错 1->表示该命名未注册,不在命名服务系统中
*/
public int canceled(String name) {
String path = nameRoot + "/" + name;
int ret = 0;
try {
if (zk.exists(path, false) == null) {
zk.delete(name, -1); // -1表示匹配所有版本
System.out.println(name + " canceled success");
} else {
ret = 1;
System.out.println(name + " is exists, can not canceled");
}
} catch (KeeperException | InterruptedException e) {
ret = -1;
e.printStackTrace();
}
return ret;
}
/**
* 读取所有信息
* @return
*/
public List<String> readAll() {
List<String> namelist = new ArrayList<String>();
try {
namelist = zk.getChildren(nameRoot, false);
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return namelist;
}
/**
* testWatcher
*/
public void testWatcher() {
TestWatcher watcher = new TestWatcher(zk, nameRoot);
Stat s = null;
try {
if ((s = zk.exists(nameRoot, watcher)) != null) {
zk.setData(nameRoot, "10.0.0.0".getBytes(), s.getVersion());
}
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public class TestWatcher implements Watcher {
private ZooKeeper zk;
private String path;
public TestWatcher(ZooKeeper zk, String path) {
this.zk = zk;
this.path = path;
}
@Override
public void process(WatchedEvent event) {
System.out.println("Path=" + event.getPath());
System.out.println("KeeperState" + event.getState());
System.out.println("EventType" + event.getType());
try {
zk.exists(path, this); // zk中一个watcher只能watch一次,之后需要重新watch
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void getAcl() {
Stat s = null;
try {
if ((s = zk.exists(nameRoot, false)) != null) {
List<ACL> acl = zk.getACL(nameRoot, s);
for (ACL a : acl) {
System.out.println("id=" + a.getId());
System.out.println("perm=" + a.getPerms()); //perm返回的结果是十进制,acl是二进制1111=31
}
}
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 获取zk指定集群ip的集群状态
* 通过srvr指令获取
* @param hostStr
* @param portStr
* @return
*/
public static String getServerState(String hostStr, String portStr) {
final String host = hostStr;
final int port = Integer.parseInt(portStr);
final String cmd = "srvr";
if (host.isEmpty() || host == null || port < 1024 || port > 65535) {
return "";
}
Socket socket = null;
OutputStream outputStream = null;
BufferedReader reader = null;
try {
InetAddress inetAddress = InetAddress.getByName(host);
socket = new Socket(inetAddress, port);
socket.setSoTimeout(30000);
outputStream = socket.getOutputStream();
outputStream.write(cmd.getBytes());
outputStream.flush();
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}
}