1.zookeeper简介
1.1什么是zookeeper
1.2 zookeeper应用场景
2.zookeeper的数据模型
3.zookeeper单机安装
4.zookeeper常用Shell命令
4.2创建节点
./zkCli.sh:首先进入客户端:
![外链图片转存失败,源站可能有防盗在这里插入!链机制,建描述]议将图片上https://传(im-logiCbZMysdnimg.cn/2021032423073642.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MTIzODY2NQ==,size_16,color_FFFFFF,t_70)https://img-blog.csdnimg参.cn/2021032423073642.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MTIzODY2NQ==,size_16,color_FFFFFF,t_70)]
4.2更新节点
4.3删除节点
4.4查看节点状态
4.5监听器
5.zookeeper的acl权限控制
*IP授权模式
命令
6.zookeeper javaAPI
zookeeper连接时,服务器端得防火墙得端口是否开放例如2181等(这里可以尝试关掉防火墙进行验证) firewall-cmd --state #查看防火墙是否关闭 systemctl stop|start firewalld.service #关掉(重启)防火墙
package com.company;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import java.util.concurrent.CountDownLatch;
public class ZookeeperConnection {
public static void main(String[] args) {
try{
//计数器对象
CountDownLatch countDownLatch=new CountDownLatch(1);
//arg1:服务器的ip和端口
//arg2:客户端与服务端的会话超时时间 以毫秒为单位的
//arg3:监视器对象
//这里要关掉linux的防火墙 systemctl stop firewalld.service
ZooKeeper zooKeeper = new ZooKeeper("192.168.28.175:2181", 5000, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getState() == Event.KeeperState.SyncConnected) {
System.out.println("连接创建成功!");
countDownLatch.countDown();
}
}
});
//主线程阻塞等待对象的创建成功
countDownLatch.await();
//会话编号
System.out.println(zooKeeper.getSessionId());
zooKeeper.close();
}catch (Exception e){
}
}
}
package com.company;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.security.acl.Acl;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class ZkCreate {
String IP="192.168.28.175:2181";
ZooKeeper zooKeeper;
@Before
public void before() throws Exception{
//计数器对象
CountDownLatch countDownLatch=new CountDownLatch(1);
//arg1:服务器的ip和端口
//arg2:客户端与服务端的会话超时时间 以毫秒为单位的
//arg3:监视器对象
//这里要关掉linux的防火墙 systemctl stop firewalld.service
zooKeeper = new ZooKeeper(IP, 5000, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getState() == Event.KeeperState.SyncConnected) {
System.out.println("连接创建成功!");
countDownLatch.countDown();
}
}
});
//主线程阻塞等待对象的创建成功
countDownLatch.await();
}
@Test
public void create1() throws Exception{
//arg1:节点的路径
//arg2:节点的数据
//arg3:权限列表 word:anyone:cdrwa
//arg4:节点类型 持久化节点
zooKeeper.create("/create/node1","node1".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
}
@Test
public void create2() throws Exception{
//arg1:节点的路径
//arg2:节点的数据
//arg3:权限列表 word:anyone:r
//arg4:节点类型 持久化节点
zooKeeper.create("/create/node2","node2".getBytes(),ZooDefs.Ids.READ_ACL_UNSAFE,CreateMode.PERSISTENT);
}
@Test
public void create3() throws Exception{
//word授权模式
//权限列表
List<ACL> acls = new ArrayList<ACL>();
//授权模式和授权对象
Id id = new Id("world", "anyone");
//权限设置
acls.add(new ACL(ZooDefs.Perms.READ,id));
acls.add(new ACL(ZooDefs.Perms.WRITE,id));
zooKeeper.create("/create/node3","node3".getBytes(),acls,CreateMode.PERSISTENT);
}
@Test
public void create4() throws Exception{
//ip授权模式
//权限列表
List<ACL> acls = new ArrayList<ACL>();
//授权模式和授权对象
Id id = new Id("ip", "192.168.60.130");
//权限设置
acls.add(new ACL(ZooDefs.Perms.ALL,id));
zooKeeper.create("/create/node4","node4".getBytes(),acls,CreateMode.PERSISTENT);
}
@Test
public void create5() throws Exception{
//auth授权模式
//添加授权用户
zooKeeper.addAuthInfo("digest","itcast:123456".getBytes());
zooKeeper.create("/create/node5","node5".getBytes(),ZooDefs.Ids.CREATOR_ALL_ACL,CreateMode.PERSISTENT);
}
@Test
public void create6() throws Exception{
//auth授权模式
//添加授权用户
zooKeeper.addAuthInfo("digest","itcast:123456".getBytes());
//权限列表
List<ACL> acls = new ArrayList<>();
//授权模式和授权对象
Id id = new Id("auth", "itcast");
//权限设置
acls.add(new ACL(ZooDefs.Perms.READ,id));
zooKeeper.create("/create/node6","node6".getBytes(),acls,CreateMode.PERSISTENT);
}
@Test
public void create7() throws Exception{
//digest授权模式
//权限列表
List<ACL> acls = new ArrayList<>();
//授权模式和授权对象 qlzQzCLKhBROghkooLvb+M1wv4A=
Id id = new Id("digest", "itheima:qlzQzCLKhBROghkooLvb+M1wv4A=");
//权限设置
acls.add(new ACL(ZooDefs.Perms.ALL,id));
zooKeeper.create("/create/node7","node7".getBytes(),acls,CreateMode.PERSISTENT);
}
@Test
public void create8() throws Exception{
//持久化顺序节点
//Ids.OPEN_ACL_UNSAFE world:anyone:cdrwa
String result = zooKeeper.create("/create/node8", "node8".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println(result);
}
@Test
public void create9() throws Exception{
//临时节点
//Ids.OPEN_ACL_UNSAFE world:anyone:cdrwa
String result = zooKeeper.create("/create/node9", "node9".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
System.out.println(result);
}
@Test
public void create10() throws Exception{
//临时顺序节点
//Ids.OPEN_ACL_UNSAFE world:anyone:cdrwa
String result = zooKeeper.create("/create/node10", "node10".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println(result);
}
@Test
public void create11() throws Exception{
//异步方式创建节点
zooKeeper.create("/create/node11", "node11".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, new AsyncCallback.StringCallback() {
@Override
public void processResult(int rc, String path, Object ctx, String name) {
//0代表创建成功
System.out.println(rc);
//节点的路径
System.out.println(path);
//节点的名称
System.out.println(name);
//上下文参数
System.out.println(ctx);
}
},"I am context");
Thread.sleep(10000);
System.out.println("结束");
}
@After
public void after() throws Exception{
zooKeeper.close();
}
}
6.3.更新节点
package com.company;
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
public class ZKSet {
String IP="192.168.28.175:2181";
ZooKeeper zooKeeper;
@Before
public void before() throws Exception{
//计数器对象
CountDownLatch countDownLatch=new CountDownLatch(1);
//arg1:服务器的ip和端口
//arg2:客户端与服务端的会话超时时间 以毫秒为单位的
//arg3:监视器对象
//这里要关掉linux的防火墙 systemctl stop firewalld.service
zooKeeper = new ZooKeeper(IP, 5000, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getState() == Event.KeeperState.SyncConnected) {
System.out.println("连接创建成功!");
countDownLatch.countDown();
}
}
});
//主线程阻塞等待对象的创建成功
countDownLatch.await();
}
@After
public void after() throws Exception{
zooKeeper.close();
}
//同步方式
@Test
public void set1() throws Exception{
// arg1:节点的路径
// arg2:修改的数据
// arg3:数据版本号 -1代表版本号不参与更新
Stat stat = zooKeeper.setData("/set/node1", "node13".getBytes(), -1);
//当前节点的版本号
System.out.println(stat.getVersion());
}
//异步方式
@Test
public void set2() throws Exception{
zooKeeper.setData("/set/node1", "node13".getBytes(), -1, new AsyncCallback.StatCallback() {
@Override
public void processResult(int rc, String path, Object ctx, Stat stat) {
//0代表修改成功
System.out.println(rc);
//节点的路径
System.out.println(path);
//上下文参数对象
System.out.println(ctx);
//属性描述对象
System.out.println(stat.getVersion());
}
},"I am Context");
Thread.sleep(10000);
System.out.println("结束");
}
}
6.4.删除节点
package com.company;
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
public class ZKDelete {
String IP="192.168.28.175:2181";
ZooKeeper zooKeeper;
@Before
public void before() throws Exception{
//计数器对象
CountDownLatch countDownLatch=new CountDownLatch(1);
//arg1:服务器的ip和端口
//arg2:客户端与服务端的会话超时时间 以毫秒为单位的
//arg3:监视器对象
//这里要关掉linux的防火墙 systemctl stop firewalld.service
zooKeeper = new ZooKeeper(IP, 5000, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getState() == Event.KeeperState.SyncConnected) {
System.out.println("连接创建成功!");
countDownLatch.countDown();
}
}
});
//主线程阻塞等待对象的创建成功
countDownLatch.await();
}
@After
public void after() throws Exception{
zooKeeper.close();
}
@Test
public void delete1() throws Exception{
// arg1:删除节点路径
// arg2:数据版本信息 -1代表删除节点时不考虑版本信息
zooKeeper.delete("/delete/node1",-1);
}
@Test
public void delete2() throws Exception{
zooKeeper.delete("/delete/node2", -1, new AsyncCallback.VoidCallback() {
@Override
public void processResult(int rc, String path, Object ctx) {
// 0代表删除成功
System.out.println(rc);
// 节点的路径
System.out.println(path);
// 节点上下文参数对象
System.out.println(ctx);
}
},"I am Context");
Thread.sleep(10000);
System.out.println("结束");
}
}
6.5.查看节点
package com.company;
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
public class ZKGet {
String IP="192.168.28.175:2181";
ZooKeeper zooKeeper;
@Before
public void before() throws Exception{
//计数器对象
CountDownLatch countDownLatch=new CountDownLatch(1);
//arg1:服务器的ip和端口
//arg2:客户端与服务端的会话超时时间 以毫秒为单位的
//arg3:监视器对象
//这里要关掉linux的防火墙 systemctl stop firewalld.service
zooKeeper = new ZooKeeper(IP, 5000, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getState() == Event.KeeperState.SyncConnected) {
System.out.println("连接创建成功!");
countDownLatch.countDown();
}
}
});
//主线程阻塞等待对象的创建成功
countDownLatch.await();
}
@After
public void after() throws Exception{
zooKeeper.close();
}
//同步方法
@Test
public void get1() throws Exception{
Stat stat = new Stat();
byte[] bys = zooKeeper.getData("/get/node1", false, stat);
//打印数据
System.out.println(new String(bys));
//版本信息
System.out.println(stat.getVersion());
}
//异步方法
@Test
public void get2() throws Exception{
zooKeeper.getData("/get/node1", false, new AsyncCallback.DataCallback() {
@Override
public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
//0 代表读取成功
System.out.println(rc);
// 节点的路径
System.out.println(path);
// 数据
System.out.println(new String(data));
//属性对象
System.out.println(stat.getVersion());
}
},"I am Context");
Thread.sleep(10000);
System.out.println("结束");
}
}
6.6.查看子节点
package com.company;
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class ZKGetChild {
String IP="192.168.28.175:2181";
ZooKeeper zooKeeper;
@Before
public void before() throws Exception{
//计数器对象
CountDownLatch countDownLatch=new CountDownLatch(1);
//arg1:服务器的ip和端口
//arg2:客户端与服务端的会话超时时间 以毫秒为单位的
//arg3:监视器对象
//这里要关掉linux的防火墙 systemctl stop firewalld.service
zooKeeper = new ZooKeeper(IP, 5000, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getState() == Event.KeeperState.SyncConnected) {
System.out.println("连接创建成功!");
countDownLatch.countDown();
}
}
});
//主线程阻塞等待对象的创建成功
countDownLatch.await();
}
@After
public void after() throws Exception{
zooKeeper.close();
}
@Test
public void get1() throws Exception{
//同步用法
// arg1:节点的路径
List<String> lists = zooKeeper.getChildren("/get", false);
for (String list : lists) {
System.out.println(list);
}
}
@Test
public void get2() throws Exception{
//异步用法
zooKeeper.getChildren("/get", false, new AsyncCallback.ChildrenCallback() {
@Override
public void processResult(int rc, String path, Object ctx, List<String> children) {
// 0代表读取成功
System.out.println(rc);
//节点的路径
System.out.println(path);
//上下文参数对象
System.out.println(ctx);
//子节点信息
for (String str : children) {
System.out.println(str);
}
}
},"I am Context");
Thread.sleep(10000);
System.out.println("结束");
}
}
6.7.检查节点是否存在
package com.company;
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
public class ZKExists {
String IP="192.168.28.175:2181";
ZooKeeper zooKeeper;
@Before
public void before() throws Exception{
//计数器对象
CountDownLatch countDownLatch=new CountDownLatch(1);
//arg1:服务器的ip和端口
//arg2:客户端与服务端的会话超时时间 以毫秒为单位的
//arg3:监视器对象
//这里要关掉linux的防火墙 systemctl stop firewalld.service
zooKeeper = new ZooKeeper(IP, 5000, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getState() == Event.KeeperState.SyncConnected) {
System.out.println("连接创建成功!");
countDownLatch.countDown();
}
}
});
//主线程阻塞等待对象的创建成功
countDownLatch.await();
}
@After
public void after() throws Exception{
zooKeeper.close();
}
@Test
public void exists1() throws Exception{
// arg1:节点的路径
Stat stat = zooKeeper.exists("/exists1", false);
//节点的版本信息
System.out.println("ss:"+stat.getVersion());
}
@Test
public void exists2() throws Exception{
//异步用法
zooKeeper.exists("/exists1", false, new AsyncCallback.StatCallback() {
@Override
public void processResult(int rc, String path, Object ctx, Stat stat) {
//0 代表方法执行成功
System.out.println(rc);
//节点的路径
System.out.println(path);
//上下文参数
System.out.println(ctx);
//节点的版本信息
System.out.println(stat.getVersion());
}
},"I am Context");
Thread.sleep(10000);
System.out.println("结束");
}
}
7.zookeeper事件监听机制
package com.company.watcher;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
public class ZkConnectionWatcher implements Watcher {
//计数器对象
static CountDownLatch countDownLatch=new CountDownLatch(1);
//连接对象
static ZooKeeper zookeeper;
@Override
public void process(WatchedEvent event) {
try {
if(event.getType()==Event.EventType.None){
if(event.getState()==Event.KeeperState.SyncConnected){
System.out.println("连接创建成功!");
countDownLatch.countDown();
}else if(event.getState()==Event.KeeperState.Disconnected){
System.out.println("断开连接!");
}else if(event.getState()==Event.KeeperState.Expired){
System.out.println("会话超时!");
zookeeper=new ZooKeeper("192.168.28.175:2181",5000,new ZkConnectionWatcher());
}else if(event.getState()==Event.KeeperState.AuthFailed){
System.out.println("认证失败!");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
zookeeper=new ZooKeeper("192.168.28.175:2181",5000,new ZkConnectionWatcher());
//阻塞线程等待连接的创建
countDownLatch.await();
//会话id
System.out.println(zookeeper.getSessionId());
//添加授权用户
zookeeper.addAuthInfo("digest","itcast:123456".getBytes());
byte[] data = zookeeper.getData("/node2", false, null);
System.out.println(new String(data));
Thread.sleep(50000);
zookeeper.close();
System.out.println("结束");
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.company.watcher;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
public class ZKWatcherExists {
String IP="192.168.28.175:2181";
ZooKeeper zooKeeper;
@Before
public void before() throws Exception{
//计数器对象
CountDownLatch countDownLatch=new CountDownLatch(1);
//arg1:服务器的ip和端口
//arg2:客户端与服务端的会话超时时间 以毫秒为单位的
//arg3:监视器对象
//这里要关掉linux的防火墙 systemctl stop firewalld.service
zooKeeper = new ZooKeeper(IP, 6000, new Watcher() {
@Override
public void process(WatchedEvent event) {
System.out.println("连接对象的对数!");
//连接成功
if (event.getState() == Event.KeeperState.SyncConnected) {
System.out.println("连接创建成功!");
countDownLatch.countDown();
}
System.out.println("path="+event.getPath());
System.out.println("eventType="+event.getType());
}
});
//主线程阻塞等待对象的创建成功
countDownLatch.await();
}
@After
public void after() throws Exception{
zooKeeper.close();
}
@Test
public void watcherExists1() throws Exception{
// arg1:节点的路径
// arg2:使用连接对象中的watcher
zooKeeper.exists("/watcher1",true);
Thread.sleep(50000);
System.out.println("结束");
}
@Test
public void watcherExists2() throws Exception{
// arg1:节点的路径
// arg2:使用连接对象中的watcher
zooKeeper.exists("/watcher1", new Watcher() {
@Override
public void process(WatchedEvent event) {
System.out.println("自定义watcher");
System.out.println("path="+event.getPath());
System.out.println("eventType="+event.getType());
}
});
Thread.sleep(50000);
System.out.println("结束");
}
@Test
public void watcherExists3() throws Exception{
//watcher一次性
Watcher watcher = new Watcher() {
@Override
public void process(WatchedEvent event) {
try {
System.out.println("自定义watcher");
System.out.println("path="+event.getPath());
System.out.println("eventType="+event.getType());
zooKeeper.exists("/watcher1",this);//这个的作用是将一次性的watcher变成多次性的watcher
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
zooKeeper.exists("/watcher1",watcher);
Thread.sleep(80000);
System.out.println("结束");
}
@Test
public void watcherExists4() throws Exception{
//注册多个监听器对象
zooKeeper.exists("/watcher1", new Watcher() {
@Override
public void process(WatchedEvent event) {
System.out.println("1");
System.out.println("path="+event.getPath());
System.out.println("eventType="+event.getType());
}
});
zooKeeper.exists("/watcher1", new Watcher() {
@Override
public void process(WatchedEvent event) {
System.out.println("2");
System.out.println("path="+event.getPath());
System.out.println("eventType="+event.getType());
}
});
Thread.sleep(80000);
System.out.println("结束");
}
}
package com.company.watcher;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
public class ZKWatcherGetData {
String IP="192.168.28.175:2181";
ZooKeeper zooKeeper;
@Before
public void before() throws Exception{
//计数器对象
CountDownLatch countDownLatch=new CountDownLatch(1);
//arg1:服务器的ip和端口
//arg2:客户端与服务端的会话超时时间 以毫秒为单位的
//arg3:监视器对象
//这里要关掉linux的防火墙 systemctl stop firewalld.service
zooKeeper = new ZooKeeper(IP, 6000, new Watcher() {
@Override
public void process(WatchedEvent event) {
System.out.println("连接对象的对数!");
//连接成功
if (event.getState() == Event.KeeperState.SyncConnected) {
countDownLatch.countDown();
}
System.out.println("path="+event.getPath());
System.out.println("eventType="+event.getType());
}
});
//主线程阻塞等待对象的创建成功
countDownLatch.await();
}
@After
public void after() throws Exception{
zooKeeper.close();
}
@Test
public void watcherGetData1() throws Exception{
// arg1:节点的路径
// arg2: 使用连接对象中的watcher
zooKeeper.getData("/watcher2",true,null);
Thread.sleep(50000);
System.out.println("结束");
}
@Test
public void watcherGetData2() throws Exception{
// arg1:节点的路径
// arg2:自定义watcher对象
zooKeeper.getData("/watcher2", new Watcher() {
@Override
public void process(WatchedEvent event) {
System.out.println("自定义watcher");
System.out.println("path="+event.getPath());
System.out.println("evnetType="+event.getType());
}
},null);
Thread.sleep(50000);
System.out.println("结束");
}
@Test
public void watcherGetData3() throws Exception{
//一次性
Watcher watcher = new Watcher() {
@Override
public void process(WatchedEvent event) {
try {
System.out.println("自定义watcher");
System.out.println("path=" + event.getPath());
System.out.println("eventType=" + event.getType());
if(event.getType()==Event.EventType.NodeDataChanged){
zooKeeper.getData("/watcher2",this,null);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
zooKeeper.getData("/watcher2",watcher,null);
Thread.sleep(50000);
System.out.println("结束");
}
@Test
public void watcherGetData4() throws Exception{
//一个节点注册多个监听器对象
zooKeeper.getData("/watcher2", new Watcher() {
@Override
public void process(WatchedEvent event) {
try {
System.out.println("1");
System.out.println("path=" + event.getPath());
System.out.println("eventType=" + event.getType());
if(event.getType()==Event.EventType.NodeDataChanged){
zooKeeper.getData("/watcher2",this,null);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},null);
zooKeeper.getData("/watcher2", new Watcher() {
@Override
public void process(WatchedEvent event) {
try {
System.out.println("2");
System.out.println("path=" + event.getPath());
System.out.println("eventType=" + event.getType());
if(event.getType()==Event.EventType.NodeDataChanged){
zooKeeper.getData("/watcher2",this,null);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},null);
Thread.sleep(50000);
System.out.println("结束");
}
}
7.6.3.查看子节点
package com.company.watcher;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
public class ZkWatcherGetChild {
String IP="192.168.28.175:2181";
ZooKeeper zooKeeper;
@Before
public void before() throws Exception{
//计数器对象
CountDownLatch countDownLatch=new CountDownLatch(1);
//arg1:服务器的ip和端口
//arg2:客户端与服务端的会话超时时间 以毫秒为单位的
//arg3:监视器对象
//这里要关掉linux的防火墙
zooKeeper = new ZooKeeper(IP, 6000, new Watcher() {
@Override
public void process(WatchedEvent event) {
System.out.println("连接对象的对数!");
//连接成功
if (event.getState() == Event.KeeperState.SyncConnected) {
System.out.println("连接创建成功!");
countDownLatch.countDown();
}
System.out.println("path="+event.getPath());
System.out.println("eventType="+event.getType());
}
});
//主线程阻塞等待对象的创建成功
countDownLatch.await();
}
@After
public void after() throws Exception{
zooKeeper.close();
}
@Test
public void watcherGetChild1() throws KeeperException, InterruptedException {
// arg1:节点的路径
// arg2:使用连接对象中的watcher
zooKeeper.getChildren("/watcher3",true);
Thread.sleep(50000);
System.out.println("结束");
}
@Test
public void watcherGetChild2() throws KeeperException, InterruptedException {
// arg1:节点的路径
// arg2:自定义watcher
zooKeeper.getChildren("/watcher3", new Watcher() {
@Override
public void process(WatchedEvent event) {
System.out.println("自定义watcher");
System.out.println("path="+event.getPath());
System.out.println("eventType="+event.getType());
}
});
Thread.sleep(50000);
System.out.println("结束");
}
@Test
public void watcherGetChild3() throws KeeperException, InterruptedException {
//一次性
Watcher watcher = new Watcher() {
@Override
public void process(WatchedEvent event) {
try {
System.out.println("自定义watcher");
System.out.println("path="+event.getPath());
System.out.println("eventType="+event.getType());
if(event.getType()==Event.EventType.NodeChildrenChanged){
zooKeeper.getChildren("/watcher3",this);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
zooKeeper.getChildren("/watcher3",watcher);
Thread.sleep(50000);
System.out.println("结束");
}
@Test
public void watcherGetChild4() throws KeeperException, InterruptedException {
//注册多个监听器
zooKeeper.getChildren("/watcher3", new Watcher() {
@Override
public void process(WatchedEvent event) {
System.out.println("1");
System.out.println("path="+event.getPath());
System.out.println("eventType="+event.getType());
}
});
zooKeeper.getChildren("/watcher3", new Watcher() {
@Override
public void process(WatchedEvent event) {
System.out.println("2");
System.out.println("path="+event.getPath());
System.out.println("eventType="+event.getType());
}
});
Thread.sleep(50000);
System.out.println("结束");
}
}
package com.company.example;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
public class MyconfigCenter implements Watcher {
// zk的字符串
String IP="192.168.28.175:2181";
//计数器对象
CountDownLatch countDownLatch=new CountDownLatch(1);
//连接对象
static ZooKeeper zooKeeper;
//用于本地化存储配置信息
private String url;
private String username;
private String password;
@Override
public void process(WatchedEvent event) {
try {
if(event.getType()==Event.EventType.None){
if(event.getState()==Event.KeeperState.SyncConnected){
System.out.println("连接成功!");
countDownLatch.countDown();
}else if(event.getState()==Event.KeeperState.Disconnected){
System.out.println("连接断开!");
}else if(event.getState()==Event.KeeperState.Expired){
System.out.println("连接超时!");
zooKeeper=new ZooKeeper("192.168.28.175:2181",5000,new MyconfigCenter());
}else if(event.getState()==Event.KeeperState.AuthFailed){
System.out.println("验证失败!");
}
}else if(event.getType()==Event.EventType.NodeDataChanged){
initValue();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public MyconfigCenter() {
initValue();
}
//连接zookeeper服务器,读取配置信息
public void initValue(){
try{
zooKeeper=new ZooKeeper(IP,50000,this);
this.url=new String(zooKeeper.getData("/config/url",true,null));
this.username=new String(zooKeeper.getData("/config/username",true,null));
this.password=new String(zooKeeper.getData("/config/password",true,null));
}catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
MyconfigCenter myconfigCenter = new MyconfigCenter();
for (int i = 0; i <20 ; i++) {
try {
Thread.sleep(5000);
System.out.println("url:"+myconfigCenter.getUrl());
System.out.println("username:"+myconfigCenter.getUsername());
System.out.println("password:"+myconfigCenter.getPassword());
System.out.println("==========================================");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
package com.company.example;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Id;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
public class GloballyUniqueId implements Watcher {
// zk的字符串
String IP="192.168.28.175:2181";
//计数器对象
CountDownLatch countDownLatch=new CountDownLatch(1);
//连接对象
static ZooKeeper zooKeeper;
// 用户生成序号的节点
String dafaultPath="/uniqueId";
//用于本地化存储配置信息
private String url;
private String username;
private String password;
@Override
public void process(WatchedEvent event) {
try {
if(event.getType()==Event.EventType.None){
if(event.getState()==Event.KeeperState.SyncConnected){
System.out.println("连接成功!");
countDownLatch.countDown();
}else if(event.getState()==Event.KeeperState.Disconnected){
System.out.println("连接断开!");
}else if(event.getState()==Event.KeeperState.Expired){
System.out.println("连接超时!");
zooKeeper=new ZooKeeper(IP,5000,new GloballyUniqueId());
}else if(event.getState()==Event.KeeperState.AuthFailed){
System.out.println("验证失败!");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public GloballyUniqueId() throws IOException {
try {
zooKeeper=new ZooKeeper(IP,5000,this);
countDownLatch.await();
} catch (Exception e) {
e.printStackTrace();
}
}
//生成id的方法
public String getUniqueId(){
String result="";
try {
//创建临时有序节点
String s = zooKeeper.create(dafaultPath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
///uniqueId*******
result=s.substring(9);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
GloballyUniqueId globallyUniqueId = null;
try {
globallyUniqueId = new GloballyUniqueId();
for (int i = 0; i <5; i++) {
String uniqueId = globallyUniqueId.getUniqueId();
System.out.println(uniqueId);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.company.example;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class MyLock {
// zk的字符串
String IP="192.168.28.175:2181";
//计数器对象
CountDownLatch countDownLatch=new CountDownLatch(1);
//连接对象
static ZooKeeper zooKeeper;
private static final String LOCK_ROOT_PATH="/Locks";
private static final String LOCK_NODE_NAME="Lock_";
private String lockPath;
//获取锁
public void acqureLock() throws Exception{
//创建锁节点
createLock();
//尝试获取锁
attemptLock();
}
public MyLock(){
try {
zooKeeper=new ZooKeeper(IP, 5000, new Watcher() {
@Override
public void process(WatchedEvent event) {
if(event.getType()==Event.EventType.None){
if(event.getState()==Event.KeeperState.SyncConnected){
System.out.println("连接成功!");
countDownLatch.countDown();
}
}
}
});
countDownLatch.await();
} catch (Exception e) {
e.printStackTrace();
}
}
//创建锁节点
private void createLock() throws KeeperException, InterruptedException {
//判断Locks是否存在,不存在则创建
Stat stat = zooKeeper.exists(LOCK_ROOT_PATH, false);
if(stat==null){
zooKeeper.create(LOCK_ROOT_PATH,new byte[0],ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
}
//创建临时有序节点
lockPath=zooKeeper.create(LOCK_ROOT_PATH+"/"+LOCK_NODE_NAME,new byte[0],ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println("节点创建成功:"+lockPath);
}
//监视器对象,判断上个节点是否删除
Watcher watch=new Watcher(){
@Override
public void process(WatchedEvent event) {
if(event.getType()==Event.EventType.NodeDeleted){
synchronized (this){
notifyAll();
}
}
}
};
//尝试获取锁
private void attemptLock() throws Exception {
//获取Locs节点下的所有子节点
List<String> list = zooKeeper.getChildren(LOCK_ROOT_PATH, false);
//对所有子节点进行排序
Collections.sort(list);
// /Locks/Lock_00000001
int index = list.indexOf(lockPath.substring(LOCK_ROOT_PATH.length() + 1));
if(index==0){
System.out.println("获取锁成功!");
return;
}else {
//上一节点的路径
String path = list.get(index - 1);
Stat stat = zooKeeper.exists(LOCK_ROOT_PATH + "/" + path, watch);
if(stat==null){
attemptLock();
}else {
synchronized (watch){
watch.wait();
}
attemptLock();
}
}
}
//释放锁
public void releaseLock() throws Exception{
//删除临时有序节点
zooKeeper.delete(this.lockPath,-1);
zooKeeper.close();
System.out.println("锁又经释放:"+this.lockPath);
}
public static void main(String[] args) {
try {
MyLock myLock = new MyLock();
myLock.createLock();
} catch (Exception e) {
e.printStackTrace();
}
}
}
测试分布式锁的例子
package com.company.example;
public class TicketSeller {
private void sell(){
System.out.println("售票开始");
//线程随机休眠毫秒,模拟现实中的费时操作
int sleepMillis=5000;
try{
//代表复杂逻辑执行了一段时间
Thread.sleep(sleepMillis);
}catch (Exception e){
e.printStackTrace();
}
System.out.println("售票结束");
}
public void sellTicketWithLock() throws Exception{
MyLock lock = new MyLock();
// 获取锁
lock.acqureLock();
sell();
// 释放锁
lock.releaseLock();
}
public static void main(String[] args) throws Exception {
TicketSeller ticketSeller = new TicketSeller();
for (int i = 0; i < 10; i++) {
ticketSeller.sellTicketWithLock();
}
}
}
8.zookeeper集群的搭建
2181
# example sakes.
dataDir=/home/zookeeper/zookeeper2181/data
# the port at which the clients will connect
clientPort=2181
server.1=192.168.28.175:2287:3387 (其中192.168.28.175为linux服务器的地址)
server.2=192.168.28.175:2288:3388
server.3=192.168.28.175:2289:3389
2182
dataDir=/home/zookeeper/zookeeper2182/data
# the port at which the clients will connect
clientPort=2182
server.1=192.168.28.175:2287:3387 (其中192.168.28.175为linux服务器的地址)
server.2=192.168.28.175:2288:3388
server.3=192.168.28.175:2289:3389
2183
dataDir=/home/zookeeper/zookeeper2183/data
# the port at which the clients will connect
clientPort=2183
server.1=192.168.28.175:2287:3387 (其中192.168.28.175为linux服务器的地址)
server.2=192.168.28.175:2288:3388
server.3=192.168.28.175:2289:3389
8.5分别启动三个集群的客户端
./zkCli.sh -server 192.168.28.175:2181
./zkCli.sh -server 192.168.28.175:2182
./zkCli.sh -server 192.168.28.175:2183
测试在某一个客户端创建一个节点,在其他两个节点分别读取,测试通过
server.3=192.168.28.175:2289:3389:observer
dataDir=/home/zookeeper/zookeeper2183/data
# the port at which the clients will connect
clientPort=2183
server.1=192.168.28.175:2287:3387
server.2=192.168.28.175:2288:3388
server.3=192.168.28.175:2289:3389:observer
peerType=observer
package com.company;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import java.util.concurrent.CountDownLatch;
public class ZookeeperConnection {
public static void main(String[] args) {
try{
//计数器对象
CountDownLatch countDownLatch=new CountDownLatch(1);
//arg1:服务器的ip和端口
//arg2:客户端与服务端的会话超时时间 以毫秒为单位的
//arg3:监视器对象
//这里要关掉linux的防火墙 systemctl stop firewalld.service
ZooKeeper zooKeeper = new ZooKeeper("192.168.28.175:2181,192.168.28.175:2182,192.168.28.175:2183", 5000, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getState() == Event.KeeperState.SyncConnected) {
System.out.println("连接创建成功!");
countDownLatch.countDown();
}
}
});
//主线程阻塞等待对象的创建成功
countDownLatch.await();
//会话编号
System.out.println(zooKeeper.getSessionId());
zooKeeper.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
创建一个maven工程,添加相关的依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.curatorApi</groupId>
<artifactId>CuratorAPI</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>2.6.0</version>
<type>jar</type>
<exclusions>
<exclusion>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.10</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.6.0</version>
<type>jar</type>
</dependency>
</dependencies>
</project>
package com.itcast.curator;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.retry.RetryNTimes;
import org.apache.curator.retry.RetryOneTime;
import org.apache.curator.retry.RetryUntilElapsed;
public class CuratorConnection {
public static void main(String[] args) {
// session重连策略
/*
3秒后重连一次,只重连1次
RetryOneTime retryOneTime = new RetryOneTime(3000);
*/
/*
每三秒重连一次,重连三次
RetryNTimes retryNTimes = new RetryNTimes(3, 3000);
*/
/*
每三秒重连一次,总等待时间超过10秒后停止重连
RetryUntilElapsed retryPolicy = new RetryUntilElapsed(10000, 3000);
*/
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
//创建连接对象
CuratorFramework client= CuratorFrameworkFactory.builder()
// IP地址端口号
.connectString("192.168.28.175:2181,192.168.28.175:2182,192.168.28.175:2183")
// 会话超时时间
.sessionTimeoutMs(5000)
// 重连机制
.retryPolicy(retryPolicy)
// 命名空间
.namespace("create")
.build();
//打开连接
client.start();
System.out.println(client.isStarted());
//关闭连接
client.close();
}
}
创建节点
package com.itcast.curator;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.security.acl.Acl;
import java.util.ArrayList;
public class CuratorCreate {
String IP="192.168.28.175:2181,192.168.28.175:2182,192.168.28.175:2183";
CuratorFramework client;
@Before
public void before() {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
//创建连接对象
client= CuratorFrameworkFactory.builder()
// IP地址端口号
.connectString(IP)
// 会话超时时间
.sessionTimeoutMs(5000)
// 重连机制
.retryPolicy(retryPolicy)
// 命名空间
.namespace("create")
.build();
//打开连接
client.start();
}
@After
public void afte(){
client.close();
}
@Test
public void create1() throws Exception{
//新增节点
client.create()
//节点的类型为持久化节点
.withMode(CreateMode.PERSISTENT)
// 节点的权限 wrod:anyone:cdrwa
.withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
.forPath("/node1","node1".getBytes());
System.out.println("结束");
}
@Test
public void create2() throws Exception{
//自定义权限列表
//权限列表
ArrayList<ACL> list = new ArrayList<ACL>();
//授权模式和授权对象
Id id=new Id("ip","192.168.28.175");
list.add(new ACL(ZooDefs.Perms.ALL,id));
client.create().withMode(CreateMode.PERSISTENT).withACL(list)
.forPath("/node2","node2".getBytes());
System.out.println("结束");
}
@Test
public void create3() throws Exception{
//递归创建节点
client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT)
.withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
.forPath("/node3/node31","node31".getBytes());
System.out.println("结束");
}
@Test
public void create4() throws Exception{
//异步方式创建节点
client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT)
.withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
.inBackground(new BackgroundCallback() {
public void processResult(CuratorFramework curatorFramework, CuratorEvent event) throws Exception {
//节点路径
System.out.println(event.getPath());
//节点的类型
System.out.println(event.getType());
}
}).forPath("/node4","node4".getBytes());
System.out.println("结束");
}
}
修改节点
package com.itcast.curator;
import com.sun.corba.se.pept.transport.Acceptor;
import com.sun.corba.se.pept.transport.Connection;
import com.sun.corba.se.pept.transport.InboundConnectionCache;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
public class CuratorSet {
String IP="192.168.28.175:2181,192.168.28.175:2182,192.168.28.175:2183";
CuratorFramework client;
@Before
public void before() {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
//创建连接对象
client= CuratorFrameworkFactory.builder()
// IP地址端口号
.connectString(IP)
// 会话超时时间
.sessionTimeoutMs(5000)
// 重连机制
.retryPolicy(retryPolicy)
// 命名空间
.namespace("set")
.build();
//打开连接
client.start();
}
@After
public void after(){
client.close();
}
@Test
public void set1() throws Exception{
client.setData()
// arg1:节点的路径
// arg2:节点的数据
.forPath("/node1","node11".getBytes());
System.out.println("结束");
}
@Test
public void set2() throws Exception{
client.setData()
//指定版本
.withVersion(-1)
.forPath("/node1","node111".getBytes());
}
@Test
public void set3() throws Exception{
client.setData().withVersion(-1).inBackground(new BackgroundCallback() {
public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
//打印节点的路径
System.out.println(curatorEvent.getPath());
// 事件的类型
System.out.println(curatorEvent.getType());
}
}).forPath("/node1","node1".getBytes());
Thread.sleep(5000);
System.out.println("结束");
}
}
删除节点
package com.itcast.curator;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class CuratorDelete {
String IP="192.168.28.175:2181,192.168.28.175:2182,192.168.28.175:2183";
CuratorFramework client;
@Before
public void before() {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
//创建连接对象
client= CuratorFrameworkFactory.builder()
// IP地址端口号
.connectString(IP)
// 会话超时时间
.sessionTimeoutMs(5000)
// 重连机制
.retryPolicy(retryPolicy)
// 命名空间
.namespace("delete")
.build();
//打开连接
client.start();
}
@After
public void after(){
client.close();
}
@Test
public void delete1() throws Exception{
// 删除节点
client.delete()
// 节点的路径
.forPath("/node1");
System.out.println("结束");
}
@Test
public void delete2() throws Exception{
client.delete()
//版本号
.withVersion(0)
// 节点的路径
.forPath("/node1");
}
@Test
public void delete3() throws Exception{
//删除包含子节点的节点
client.delete().deletingChildrenIfNeeded()
.withVersion(0)
.forPath("/node1");
}
@Test
public void delete4() throws Exception{
// 异步删除包含子节点的节点
client.delete()
.deletingChildrenIfNeeded()
.withVersion(-1)
.inBackground(new BackgroundCallback() {
public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
// 节点的路径
System.out.println(curatorEvent.getPath());
}
})
.forPath("/node1");
Thread.sleep(5000);
System.out.println("结束");
}
}
通过Curator客户端查看节点数据
package com.itcast.curator;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
public class CuratorGetChild {
String IP="192.168.28.175:2181,192.168.28.175:2182,192.168.28.175:2183";
CuratorFramework client;
@Before
public void before() {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
//创建连接对象
client= CuratorFrameworkFactory.builder()
// IP地址端口号
.connectString(IP)
// 会话超时时间
.sessionTimeoutMs(5000)
// 重连机制
.retryPolicy(retryPolicy)
// 命名空间
.build();
//打开连接
client.start();
}
@After
public void after(){
client.close();
}
@Test
public void get1() throws Exception{
//读取节点的数据
List<String> lists = client.getChildren()
//节点路径
.forPath("/get");
for (String list : lists) {
System.out.println(list);
}
}
@Test
public void get2() throws Exception{
//异步的方式读取子节点的数据
client.getChildren()
.inBackground(new BackgroundCallback() {
public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
//节点的路径
System.out.println(curatorEvent.getPath());
// 节点的类型
System.out.println(curatorEvent.getType());
// 节点的数据
List<String> lists = curatorEvent.getChildren();
for (String list : lists) {
System.out.println(list);
}
}
})
.forPath("/get");
Thread.sleep(5000);
System.out.println("结束");
}
@Test
public void get3() throws Exception{
}
}
检查节点
package com.itcast.curator;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
public class CuratorExists {
String IP="192.168.28.175:2181,192.168.28.175:2182,192.168.28.175:2183";
CuratorFramework client;
@Before
public void before() {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
//创建连接对象
client= CuratorFrameworkFactory.builder()
// IP地址端口号
.connectString(IP)
// 会话超时时间
.sessionTimeoutMs(5000)
// 重连机制
.retryPolicy(retryPolicy)
// 命名空间
.namespace("get")
.build();
//打开连接
client.start();
}
@After
public void after(){
client.close();
}
@Test
public void get1() throws Exception{
//检查节点是否存在
Stat stat = client.checkExists()
.forPath("/node3");
System.out.println(stat);
}
@Test
public void get2() throws Exception{
// 异步方式检查节点是否存在
client.checkExists()
.inBackground(new BackgroundCallback() {
public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
// 节点的类型
System.out.println(curatorEvent.getType());
// 事件类型
System.out.println(curatorEvent.getPath());
System.out.println(curatorEvent.getStat().getVersion());
}
})
.forPath("/node3");
Thread.sleep(5000);
System.out.println("结束");
}
@Test
public void get3() throws Exception{
}
}
8.9watchAPI
package com.itcast.curator;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class CuratorWatch {
String IP="192.168.28.175:2181,192.168.28.175:2182,192.168.28.175:2183";
CuratorFramework client;
@Before
public void before() {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
//创建连接对象
client= CuratorFrameworkFactory.builder()
// IP地址端口号
.connectString(IP)
// 会话超时时间
.sessionTimeoutMs(5000)
// 重连机制
.retryPolicy(retryPolicy)
.build();
//打开连接
client.start();
}
@Test
public void watch1() throws Exception{
//监视某个节点的数据变化
// arg1:连接对象
// arg2:节点的路径
final NodeCache nodeCache = new NodeCache(client,"/watcher1");
// 启动监视器对象
nodeCache.start();
nodeCache.getListenable().addListener(new NodeCacheListener() {
// 节点变化时回调的方法
public void nodeChanged() throws Exception {
System.out.println(nodeCache.getCurrentData().getPath());
System.out.println(new String(nodeCache.getCurrentData().getData()));
}
});
Thread.sleep(100000);
System.out.println("结束");
// 关闭监视器对象
nodeCache.close();
}
@After
public void after(){
client.close();
}
@Test
public void watch2() throws Exception{
// 监视子节点的变化
// arg1:连接对象
// arg2:监视的节点路径
// arg3:事件中是否可以获取节点的数据
PathChildrenCache childrenCache = new PathChildrenCache(client, "/watcher1", true);
// 启动监听
childrenCache.start();
childrenCache.getListenable().addListener(new PathChildrenCacheListener() {
//当子节点发生变化时回调的方法
public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
// 节点的路径
System.out.println(pathChildrenCacheEvent.getData().getPath());
// 节点数据
System.out.println(new String(pathChildrenCacheEvent.getData().getData()));
}
});
Thread.sleep(100000);
System.out.println("结束");
// 关闭监听
childrenCache.close();
}
@Test
public void watch3() throws Exception{
}
}
8.10事务
package com.itcast.curator;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class CuratorTransaction {
String IP="192.168.28.175:2181,192.168.28.175:2182,192.168.28.175:2183";
CuratorFramework client;
@Before
public void before() {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
//创建连接对象
client= CuratorFrameworkFactory.builder()
// IP地址端口号
.connectString(IP)
// 会话超时时间
.sessionTimeoutMs(5000)
// 重连机制
.retryPolicy(retryPolicy)
.namespace("create")
.build();
//打开连接
client.start();
}
@After
public void after(){
client.close();
}
@Test
public void tra1() throws Exception{
client.inTransaction().create().forPath("/node1","node1".getBytes())
.and()
.setData().forPath("/node2","node2".getBytes()).and()
.commit();
}
@Test
public void watch2() throws Exception{
}
@Test
public void watch3() throws Exception{
}
}
8.12分布式锁
package com.itcast.curator;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMultiLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.framework.recipes.locks.InterProcessReadWriteLock;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class CuratorLock {
String IP="192.168.28.175:2181,192.168.28.175:2182,192.168.28.175:2183";
CuratorFramework client;
@Before
public void before() {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
//创建连接对象
client= CuratorFrameworkFactory.builder()
// IP地址端口号
.connectString(IP)
// 会话超时时间
.sessionTimeoutMs(5000)
// 重连机制
.retryPolicy(retryPolicy)
.build();
//打开连接
client.start();
}
@Test
public void watch1() throws Exception{
// 排他锁
InterProcessLock interProcessLock=new InterProcessMutex(client,"/lock1");
System.out.println("等待获取锁对象");
// 获取锁
interProcessLock.acquire();
for (int i = 1; i <=10 ; i++) {
Thread.sleep(3000);
System.out.println(i);
}
// 释放锁
interProcessLock.release();
System.out.println("等待释放锁");
//
}
@After
public void after(){
client.close();
}
@Test
public void lock2() throws Exception{
// 读写锁
InterProcessReadWriteLock interProcessReadWriteLock=new InterProcessReadWriteLock(client,"/lock1");
// 获取读锁对象
InterProcessLock interProcessLock = interProcessReadWriteLock.readLock();
System.out.println("等待获取锁对象");
// 获取锁
interProcessLock.acquire();
for (int i = 1; i <=10 ; i++) {
Thread.sleep(3000);
System.out.println(i);
}
// 释放锁
interProcessLock.release();
System.out.println("等待释放锁");
}
@Test
public void lock3() throws Exception{
// 读写锁
InterProcessReadWriteLock interProcessReadWriteLock=new InterProcessReadWriteLock(client,"/lock1");
// 获取写锁对象
InterProcessLock interProcessLock = interProcessReadWriteLock.writeLock();
System.out.println("等待获取锁对象");
// 获取锁
interProcessLock.acquire();
for (int i = 1; i <=10 ; i++) {
Thread.sleep(3000);
System.out.println(i);
}
// 释放锁
interProcessLock.release();
System.out.println("等待释放锁");
}
}
zookeeper四字监控命令
加粗样式
> wchc命令
fi
else
echo "JMX disabled by user request" >&2
ZOOMAIN="org.apache.zookeeper.server.quorum.QuorumPeerMain"
fi
在上面的这个代码下面添加如下的代码:
ZOOMAIN="-Dzookeeper.4lw.commands.whitelist=* ${ZOOMAIN}"
wchc 命令
wchp命令
mntr命令