- 本文的使用都是在SpringBoot里面使用
@Test
进行的测试
建立连接
public ZooKeeper(String connectString, int sessionTimeout, Watcher watcher)
String connectString
:是ZooKeeper服务器的IP+端口号,多个就用,
分割。例如"127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002"
int sessionTimeout
:Session的超时时间或者是心跳时间,毫秒为单位Watcher watcher
:注册的 watcher,一旦在本次子节点获取后,子节点列表发生变更的话,那么就会向客户端发送通知。这个参数也可以为null
,但是会报java.lang.NullPointerException: null
的异常,但并不影响使用
@Test
public void myConnect() throws Exception{
ZooKeeper zooKeeper=new ZooKeeper(zkServerPath, timeout, new ZookeeperTestApplicationTests());
log.warn("Connection Status: {}", zooKeeper.getState());
new Thread().sleep(2000);
log.warn("Connection Status: {}", zooKeeper.getState());
}
输出结果
2019-02-26 17:56:19.355 WARN 14304 --- [ main] c.l.z.ZookeeperTestApplicationTests : Connection Status: CONNECTING
2019-02-26 17:56:19.363 INFO 14304 --- [04.34.155:2183)] org.apache.zookeeper.ClientCnxn : Opening socket connection to server 129.204.34.155/129.204.34.155:2183. Will not attempt to authenticate using SASL (unknown error)
2019-02-26 17:56:19.388 INFO 14304 --- [04.34.155:2183)] org.apache.zookeeper.ClientCnxn : Socket connection established to 129.204.34.155/129.204.34.155:2183, initiating session
2019-02-26 17:56:19.426 INFO 14304 --- [04.34.155:2183)] org.apache.zookeeper.ClientCnxn : Session establishment complete on server 129.204.34.155/129.204.34.155:2183, sessionid = 0x300002031ca0018, negotiated timeout = 5000
2019-02-26 17:56:19.429 WARN 14304 --- [ain-EventThread] c.l.z.ZookeeperTestApplicationTests : Receive Watch: WatchedEvent state:SyncConnected type:None path:null
2019-02-26 17:56:21.360 WARN 14304 --- [ main] c.l.z.ZookeeperTestApplicationTests : Connection Status: CONNECTED
从输出的日志可以看出需要线程sleep一下,来等待连接
创建节点
public void create(final String path, byte data[], List<ACL> acl,
CreateMode createMode, StringCallback cb, Object ctx)
final String path
:节点的路径名byte data[]
:节点的数据List<ACL> acl
:节点的权限CreateMode createMode
:节点的类型StringCallback cb
:回调函数Object ctx
:信息
创建节点有异步和同步两种:同一个方法,但是同步的参数没有回调函数和信息
//异步的方式
@Test
public void myCreate() throws Exception{
ZooKeeper zooKeeper=new ZooKeeper(zkServerPath, timeout, new ZookeeperTestApplicationTests());
new Thread().sleep(2000);
log.warn("Connection Status:{}", zooKeeper.getState());
String ctx="{'Create': 'Success'}";
zooKeeper.create("/test", "lsc".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT, new CreateCallBack(), ctx);
}
获取节点数据
public byte[] getData(String path, boolean watch, Stat stat)
String path
:目标节点路径名boolean watch
:是否监控节点的数据状态Stat stat
:数据的信息- 返回值是节点的数据
@Test
public void myGetData() throws Exception{
ZooKeeper zooKeeper=new ZooKeeper(zkServerPath, timeout, new ZookeeperTestApplicationTests());
new Thread().sleep(2000);
log.warn("Connection Status:{}", zooKeeper.getState());
byte[] data=zooKeeper.getData("/test", false, null);
System.out.println(new String(data));
}
控制台输出了/test
这个节点的数据为lsc
设置节点数据
public Stat setData(final String path, byte data[], int version)
final String path
:目标节点的路径名byte data[]
:设置的数据int version
:数据的版本号,可以用-1来匹配任何版本- 返回值:节点的信息
@Test
public void mySetData() throws Exception{
ZooKeeper zooKeeper=new ZooKeeper(zkServerPath, timeout, new ZookeeperTestApplicationTests());
new Thread().sleep(2000);
log.warn("Connection Status:{}", zooKeeper.getState());
System.out.println(zooKeeper.setData("/test", "ValarMorghulis".getBytes(), -1));
}
获取节点的子节点
public List<String> getChildren(String path, boolean watch)
String path
:父节点的路径名boolean watch
:是否监控子节点的状态- 返回值:子节点的名称
@Test
public void myGetChildren() throws Exception{
ZooKeeper zooKeeper=new ZooKeeper(zkServerPath, timeout, new ZookeeperTestApplicationTests());
new Thread().sleep(2000);
log.warn("Connection Status:{}", zooKeeper.getState());
System.out.println(zooKeeper.getChildren("/", false));
}
判断节点是否存在
public Stat exists(String path, boolean watch)
String path
:目标节点的路径名boolean watch
:是否监控这个节点- 返回值:节点的状态信息;不存在这个节点就返回
null
@Test
public void myExists() throws Exception{
ZooKeeper zooKeeper=new ZooKeeper(zkServerPath, timeout, new ZookeeperTestApplicationTests());
new Thread().sleep(2000);
log.warn("Connection Status:{}", zooKeeper.getState());
System.out.println(zooKeeper.exists("/test", false));
}
删除节点
public void delete(final String path, int version)
final String path
:目标节点的路径名int version
:节点的版本,可以用-1匹配任何版本
@Test
public void myDelete() throws Exception{
ZooKeeper zooKeeper=new ZooKeeper(zkServerPath, timeout, new ZookeeperTestApplicationTests());
new Thread().sleep(2000);
log.warn("Connection Status:{}", zooKeeper.getState());
zooKeeper.delete("/test", -1);
}
获取节点权限信息
public List<ACL> getACL(final String path, Stat stat)
final String path
:目标节点路径名Stat stat
:节点信息- 返回值:节点的权限信息
@Test
public void myGetAcl() throws Exception{
ZooKeeper zooKeeper=new ZooKeeper(zkServerPath, timeout, new ZookeeperTestApplicationTests());
new Thread().sleep(2000);
log.warn("Connection Status:{}", zooKeeper.getState());
List<ACL> acls=zooKeeper.getACL("/test", null);
for (ACL acl:acls){
System.out.println(acl);
}
}
设置节点权限&提交自己的授权信息
public Stat setACL(final String path, List<ACL> acl, int aclVersion)
final String path
:目标节点路径名List<ACL> acl
:设置的权限int aclVersion
:版本号- 返回值:节点的信息
public void addAuthInfo(String scheme, byte auth[])
String scheme
:权限模式byte auth[]
:授权信息
@Test
public void mySetAcl() throws Exception{
ZooKeeper zooKeeper=new ZooKeeper(zkServerPath, timeout, new ZookeeperTestApplicationTests());
new Thread().sleep(2000);
log.warn("Connection Status:{}", zooKeeper.getState());
List<ACL> acls=new ArrayList<ACL>();
Id lsc=new Id("digest", DigestAuthenticationProvider.generateDigest("lsc:lsc"));
acls.add(new ACL(ZooDefs.Perms.ADMIN | ZooDefs.Perms.WRITE | ZooDefs.Perms.READ, lsc));
zooKeeper.addAuthInfo("digest", "lsc:lsc".getBytes());
Stat stat=zooKeeper.setACL("/test", acls, -1);
System.out.println(stat);
}
完整代码
package com.lsc.zookeepertest;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ZookeeperTestApplicationTests implements Watcher {
public static Logger log= LoggerFactory.getLogger(ZookeeperTestApplicationTests.class);
public static final String zkServerPath="129.204.34.155:2181," +
"129.204.34.155:2182,129.204.34.155:2183";
public static final Integer timeout=5000;
//连接zookeeper集群
@Test
public void myConnect() throws Exception{
ZooKeeper zooKeeper=new ZooKeeper(zkServerPath, timeout, new ZookeeperTestApplicationTests());
log.warn("Connection Status: {}", zooKeeper.getState());
new Thread().sleep(2000);
log.warn("Connection Status: {}", zooKeeper.getState());
}
//zookeeper重连
@Test
public void myReconnect() throws Exception{
ZooKeeper zooKeeper=new ZooKeeper(zkServerPath, timeout, new ZookeeperTestApplicationTests());
long sessionId=zooKeeper.getSessionId();
String ssid="0x"+Long.toHexString(sessionId);
byte[] sessionPassword=zooKeeper.getSessionPasswd();
log.warn("Begin Connecting...");
log.warn("Connection Status:{}", zooKeeper.getState());
new Thread().sleep(1000);
log.warn("Connection Status:{}", zooKeeper.getState());
new Thread().sleep(200);
log.warn("Begin Session Reconnecting...");
ZooKeeper zkSession = new ZooKeeper(zkServerPath,
timeout,
new ZookeeperTestApplicationTests(),
sessionId,
sessionPassword);
log.warn("Session Reconnect Status:{}", zkSession.getState());
new Thread().sleep(1000);
log.warn("Session Reconnect Status:{}", zkSession.getState());
}
//zookeeper创建节点
@Test
public void myCreate() throws Exception{
ZooKeeper zooKeeper=new ZooKeeper(zkServerPath, timeout, new ZookeeperTestApplicationTests());
new Thread().sleep(2000);
log.warn("Connection Status:{}", zooKeeper.getState());
String ctx="{'Create': 'Success'}";
zooKeeper.create("/test", "lsc".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT, new CreateCallBack(), ctx);
}
//zookeeper获取节点信息
@Test
public void myGetData() throws Exception{
ZooKeeper zooKeeper=new ZooKeeper(zkServerPath, timeout, new ZookeeperTestApplicationTests());
new Thread().sleep(2000);
log.warn("Connection Status:{}", zooKeeper.getState());
byte[] data=zooKeeper.getData("/test", false, null);
System.out.println(new String(data));
}
//zookeeper获取节点的子节点
@Test
public void myGetChildren() throws Exception{
ZooKeeper zooKeeper=new ZooKeeper(zkServerPath, timeout, new ZookeeperTestApplicationTests());
new Thread().sleep(2000);
log.warn("Connection Status:{}", zooKeeper.getState());
System.out.println(zooKeeper.getChildren("/", false));
}
//zookeeper设置节点数据
@Test
public void mySetData() throws Exception{
ZooKeeper zooKeeper=new ZooKeeper(zkServerPath, timeout, new ZookeeperTestApplicationTests());
new Thread().sleep(2000);
log.warn("Connection Status:{}", zooKeeper.getState());
System.out.println(zooKeeper.setData("/test", "ValarMorghulis".getBytes(), -1));
}
//判断节点是否存在
@Test
public void myExists() throws Exception{
ZooKeeper zooKeeper=new ZooKeeper(zkServerPath, timeout, new ZookeeperTestApplicationTests());
new Thread().sleep(2000);
log.warn("Connection Status:{}", zooKeeper.getState());
System.out.println(zooKeeper.exists("/test", false));
}
//zookeeper删除节点
@Test
public void myDelete() throws Exception{
ZooKeeper zooKeeper=new ZooKeeper(zkServerPath, timeout, new ZookeeperTestApplicationTests());
new Thread().sleep(2000);
log.warn("Connection Status:{}", zooKeeper.getState());
zooKeeper.delete("/test", -1);
}
//zookeeper获取节点权限
@Test
public void myGetAcl() throws Exception{
ZooKeeper zooKeeper=new ZooKeeper(zkServerPath, timeout, new ZookeeperTestApplicationTests());
new Thread().sleep(2000);
log.warn("Connection Status:{}", zooKeeper.getState());
List<ACL> acls=zooKeeper.getACL("/test", null);
for (ACL acl:acls){
System.out.println(acl);
}
}
/*
* zookeeper设置节点权限,需要权限进行设置时:
* void addAuthInfo(String scheme, byte[] auth)
* 客户端将自己的授权信息提交给服务器,服务器将根据这个授权信息验证客户端的访问权限。
*/
@Test
public void mySetAcl() throws Exception{
ZooKeeper zooKeeper=new ZooKeeper(zkServerPath, timeout, new ZookeeperTestApplicationTests());
new Thread().sleep(2000);
log.warn("Connection Status:{}", zooKeeper.getState());
List<ACL> acls=new ArrayList<ACL>();
Id lsc=new Id("digest", DigestAuthenticationProvider.generateDigest("lsc:lsc"));
acls.add(new ACL(ZooDefs.Perms.ADMIN | ZooDefs.Perms.WRITE | ZooDefs.Perms.READ, lsc));
zooKeeper.addAuthInfo("digest", "lsc:lsc".getBytes());
Stat stat=zooKeeper.setACL("/test", acls, -1);
System.out.println(stat);
}
@Override
public void process(WatchedEvent event) {
log.warn("Receive Watch: {}", event);
}
}