Zookeeper实战
这里的实战主要是用Java API对Zookeeper进行相应的操作,来实现我们的业务需求。首先简单地测试一下Zookeeper节点的增删改查操作,然后测试两个例子,分别是分布式应用HA以及分布式锁。
1. 增删改查的测试demo
首先,我们建立一个工程,导入相应的jar包依赖,如下:
然后,我们开始进行简单地测试:
package cn.darrenchan.bigdata.zk; 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.Stat;
import org.junit.Before;
import org.junit.Test; public class SimpleZkClient { private static final String connectString = "weekend01:2181,weekend02:2181,weekend03:2181";
private static final int sessionTimeout = 2000;//会话超时时间2s private ZooKeeper zkClient = null; @Before
public void init() throws Exception {
zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent event) {
// 收到事件通知后的回调函数(应该是我们自己的事件处理逻辑)
System.out.println(event.getType() + "---" + event.getPath());
try {
// 每次设成true,是因为每次只能监控一遍
zkClient.getChildren("/", true);
} catch (Exception e) {
}
}
}); } /**
* 数据的增删改查
*
* @throws InterruptedException
* @throws KeeperException
*/ // 创建数据节点到zk中
@Test
public void testCreate() throws KeeperException, InterruptedException {
// 参数1:要创建的节点的路径 参数2:节点大数据 参数3:节点的权限 参数4:节点的类型
String nodeCreated = zkClient.create("/eclipse", "hellozk".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
//上传的数据可以是任何类型,但都要转成byte[]
System.out.println(nodeCreated);
} //判断znode是否存在
@Test
public void testExist() throws Exception{
Stat stat = zkClient.exists("/eclipse", false);
System.out.println(stat==null?"not exist":"exist");
} // 获取子节点
@Test
public void getChildren() throws Exception {
List<String> children = zkClient.getChildren("/", true);
for (String child : children) {
System.out.println(child);
}
Thread.sleep(Long.MAX_VALUE);
} //获取znode的数据
@Test
public void getData() throws Exception { byte[] data = zkClient.getData("/eclipse", false, null);
System.out.println(new String(data)); } //删除znode
@Test
public void deleteZnode() throws Exception { //参数2:指定要删除的版本,-1表示删除所有版本
zkClient.delete("/eclipse", -1); }
//删除znode
@Test
public void setData() throws Exception { zkClient.setData("/eclipse", "i miss you huiru".getBytes(), -1); byte[] data = zkClient.getData("/eclipse", false, null);
System.out.println(new String(data)); } }
Zookeeper的监听器工作机制
监听器是一个接口,我们的代码中可以实现Wather这个接口,实现其中的process方法,方法中即我们自己的业务逻辑。
监听器的注册是在获取数据的操作中实现:
getData(path,watch?)监听的事件是:节点数据变化事件。
getChildren(path,watch?)监听的事件是:节点下的子节点增减变化事件。
2. 分布式应用HA
某分布式系统中,主节点可以有多台,可以动态上下线。
任意一台客户端都能实时感知到主节点服务器的上下线。
客户端实现:
package cn.darrenchan.bigdata.zkdist; import java.util.ArrayList;
import java.util.List; import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat; public class AppClient {
private String groupNode = "sgroup";
private ZooKeeper zk;
private Stat stat = new Stat();
private volatile List<String> serverList; /**
* 连接zookeeper
*/
public void connectZookeeper() throws Exception {
zk = new ZooKeeper("weekend01:2181,weekend02:2181,weekend03:2181", 2000, new Watcher() {
public void process(WatchedEvent event) {
// 如果发生了"/sgroup"节点下的子节点变化事件, 更新server列表, 并重新注册监听
if (event.getType() == EventType.NodeChildrenChanged && ("/" + groupNode).equals(event.getPath())) {
try {
updateServerList();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}); updateServerList();
} /**
* 更新server列表
*/
private void updateServerList() throws Exception {
List<String> newServerList = new ArrayList<String>(); // 获取并监听groupNode的子节点变化
// watch参数为true, 表示监听子节点变化事件.
// 每次都需要重新注册监听, 因为一次注册, 只能监听一次事件, 如果还想继续保持监听, 必须重新注册
List<String> subList = zk.getChildren("/" + groupNode, true);
for (String subNode : subList) {
// 获取每个子节点下关联的server地址
byte[] data = zk.getData("/" + groupNode + "/" + subNode, false, stat);
newServerList.add(new String(data, "utf-8"));
} // 替换server列表
serverList = newServerList; System.out.println("server list updated: " + serverList);
} /**
* client的工作逻辑写在这个方法中 此处不做任何处理, 只让client sleep
*/
public void handle() throws InterruptedException {
Thread.sleep(Long.MAX_VALUE);
} public static void main(String[] args) throws Exception {
AppClient ac = new AppClient();
ac.connectZookeeper(); ac.handle();
}
}
服务器实现:
package cn.darrenchan.bigdata.zkdist; import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper; public class AppServer {
private String groupNode = "sgroup";
private String subNode = "sub"; /**
* 连接zookeeper
*
* @param address
* server的地址
*/
public void connectZookeeper(String address) throws Exception {
ZooKeeper zk = new ZooKeeper("weekend01:2181,weekend02:2181,weekend03:2181", 2000, new Watcher() {
public void process(WatchedEvent event) {
// 不做处理
}
});
// 在"/sgroup"下创建子节点
// 子节点的类型设置为EPHEMERAL_SEQUENTIAL, 表明这是一个临时节点, 且在子节点的名称后面加上一串数字后缀
// 将server的地址数据关联到新创建的子节点上
String createdPath = zk.create("/" + groupNode + "/" + subNode, address.getBytes("utf-8"), Ids.OPEN_ACL_UNSAFE,
CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println("create: " + createdPath);
} /**
* server的工作逻辑写在这个方法中 此处不做任何处理, 只让server sleep
*/
public void handle() throws InterruptedException {
Thread.sleep(Long.MAX_VALUE);
} public static void main(String[] args) throws Exception {
// 在参数中指定server的地址
if (args.length == 0) {
System.err.println("The first argument must be server address");
System.exit(1);
} AppServer as = new AppServer();
as.connectZookeeper(args[0]);
as.handle();
}
}
3. 分布式锁
开启10个线程,按照顺序执行业务,一个执行完进而执行下一个,直到全部执行完为止。
package cn.darrenchan.bigdata.zklock; import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch; import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat; public class DistributedClient {
// 超时时间
private static final int SESSION_TIMEOUT = 5000;
// zookeeper server列表
private String hosts = "weekend01:2181,weekend02:2181,weekend03:2181";
private String groupNode = "locks";
private String subNode = "sub"; private ZooKeeper zk;
// 当前client创建的子节点
private String thisPath;
// 当前client等待的子节点
private String waitPath; private CountDownLatch latch = new CountDownLatch(1); /**
* 连接zookeeper
*/
public void connectZookeeper() throws Exception {
zk = new ZooKeeper(hosts, SESSION_TIMEOUT, new Watcher() {
public void process(WatchedEvent event) {
try {
System.out.println(event.getState()+",,,"+event.getType()+",,,"+event.getPath());
// 连接建立时, 打开latch, 唤醒wait在该latch上的线程
if (event.getState() == KeeperState.SyncConnected) {
latch.countDown();
} // 发生了waitPath的删除事件
if (event.getType() == EventType.NodeDeleted && event.getPath().equals(waitPath)) {
doSomething();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}); // 等待连接建立
latch.await(); // 创建子节点
thisPath = zk.create("/" + groupNode + "/" + subNode, null, Ids.OPEN_ACL_UNSAFE,
CreateMode.EPHEMERAL_SEQUENTIAL); // wait一小会, 让结果更清晰一些
Thread.sleep(10); // 注意, 没有必要监听"/locks"的子节点的变化情况
List<String> childrenNodes = zk.getChildren("/" + groupNode, false); // 列表中只有一个子节点, 那肯定就是thisPath, 说明client获得锁
if (childrenNodes.size() == 1) {
doSomething();
} else {
String thisNode = thisPath.substring(("/" + groupNode + "/").length());
// 排序
Collections.sort(childrenNodes);
int index = childrenNodes.indexOf(thisNode);
if (index == -1) {
// never happened
} else if (index == 0) {
// inddx == 0, 说明thisNode在列表中最小, 当前client获得锁
doSomething();
} else {
// 获得排名比thisPath前1位的节点
this.waitPath = "/" + groupNode + "/" + childrenNodes.get(index - 1);
// 在waitPath上注册监听器, 当waitPath被删除时, zookeeper会回调监听器的process方法
zk.getData(waitPath, true, new Stat());
}
}
} private void doSomething() throws Exception {
try {
System.out.println("gain lock: " + thisPath);
Thread.sleep(2000);
// do something
} finally {
System.out.println("finished: " + thisPath);
// 将thisPath删除, 监听thisPath的client将获得通知
// 相当于释放锁
zk.delete(this.thisPath, -1);
}
} public static void main(String[] args) throws Exception {
for (int i = 0; i < 10; i++) {
new Thread() {
public void run() {
try {
DistributedClient dl = new DistributedClient();
dl.connectZookeeper();
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
} Thread.sleep(Long.MAX_VALUE);
}
}
实现效果:
SyncConnected,,,None,,,null
SyncConnected,,,None,,,null
SyncConnected,,,None,,,null
SyncConnected,,,None,,,null
SyncConnected,,,None,,,null
SyncConnected,,,None,,,null
SyncConnected,,,None,,,null
SyncConnected,,,None,,,null
SyncConnected,,,None,,,null
SyncConnected,,,None,,,null
gain lock: /locks/sub0000000000
finished: /locks/sub0000000000
SyncConnected,,,NodeDeleted,,,/locks/sub0000000000
gain lock: /locks/sub0000000001
finished: /locks/sub0000000001
SyncConnected,,,NodeDeleted,,,/locks/sub0000000001
gain lock: /locks/sub0000000002
finished: /locks/sub0000000002
SyncConnected,,,NodeDeleted,,,/locks/sub0000000002
gain lock: /locks/sub0000000003
finished: /locks/sub0000000003
SyncConnected,,,NodeDeleted,,,/locks/sub0000000003
gain lock: /locks/sub0000000004
finished: /locks/sub0000000004
SyncConnected,,,NodeDeleted,,,/locks/sub0000000004
gain lock: /locks/sub0000000005
finished: /locks/sub0000000005
SyncConnected,,,NodeDeleted,,,/locks/sub0000000005
gain lock: /locks/sub0000000006
finished: /locks/sub0000000006
SyncConnected,,,NodeDeleted,,,/locks/sub0000000006
gain lock: /locks/sub0000000007
finished: /locks/sub0000000007
SyncConnected,,,NodeDeleted,,,/locks/sub0000000007
gain lock: /locks/sub0000000008
finished: /locks/sub0000000008
SyncConnected,,,NodeDeleted,,,/locks/sub0000000008
gain lock: /locks/sub0000000009
finished: /locks/sub0000000009
Zookeeper实战的更多相关文章
- zookeeper实战:SingleWorker代码样例
我们需要一个“单点worker”系统,此系统来确保系统中定时任务在分布式环境中,任意时刻只有一个实例处于活跃:比如,生产环境中,有6台机器支撑一个应用,但是一个应用中有30个定时任务,这些任务有些必须 ...
- Zookeeper实战之嵌入式执行Zookeeper集群模式
非常多使用Zookeeper的情景是须要我们嵌入Zookeeper作为自己的分布式应用系统的一部分来提供分布式服务.此时我们须要通过程序的方式来启动Zookeeper.此时能够通过Zookeeper ...
- zookeeper 实战 - Pymjer 的博客
下载 $ wget http://apache.forsale.plus/zookeeper/zookeeper-3.4.9/zookeeper-3.4.9.tar.gz 配置conf/zoo.cfg ...
- 【实战】ZooKeeper 实战
1. 前言 这篇文章简单给演示一下 ZooKeeper 常见命令的使用以及 ZooKeeper Java客户端 Curator 的基本使用.介绍到的内容都是最基本的操作,能满足日常工作的基本需要. 如 ...
- Zookeeper实战之单机模式
Zookeeper介绍 Zookeeper 分布式服务框架是用来解决分布式应用中经常遇到的一些数据管理问题,如:统一命名服务.状态同步服务.集群管理.分布式应用配置项的管理等.本文主要从使用者角度来介 ...
- Zookeeper实战之单机集群模式
前一篇文章介绍了Zookeeper的单机模式的安装及应用,但是Zookeeper是为了解决分布式应用场景的,所以通常都会运行在集群模式下.今天由于手头机器不足,所以今天打算在一台机器上部署三个Zook ...
- zookeeper 实战案例分享:cruator客户端编程
上两篇介绍了zookeeper服务器端的安装和配置,今天分享下利用zookeeper客户端编程来实现配置文件的统一管理,包括文件添加.删除.更新的同步. 比如,连接数据库信息的配置文件,一般每个应用服 ...
- kafka与zookeeper实战笔记
kafka命令 1.先启动zookeeper zkServer.cmd/zkServer.sh2.启动kafka[需要指定server.properties文件] kafka-server-start ...
- 大数据学习笔记之Zookeeper(四):Zookeeper实战篇(二)
文章目录 4.1 分布式安装部署 4.2 客户端命令行操作 4.3 API应用 4.3.1 eclipse环境搭建 4.3.2 创建ZooKeeper客户端: 4.3.3 创建子节点 4.3.4 获取 ...
随机推荐
- Spark Streaming no receivers彻底思考
数据接入Spark Streaming的二种方式:Receiver和no receivers方式 建议企业级采用no receivers方式开发Spark Streaming应用程序,好处: 1.更优 ...
- C# 获取父控件容器的属性
C# 获取父控件容器的属性 BindingNavigator bindingNavigator = (sender as ToolStripButton).GetCurrentParent() as ...
- 使用JRadioButton 示例
代码如下: JRadioButton useCache=new JRadioButton("Use cache");// 初始化单选框 useCache.setFont(new F ...
- Win7如何更改网络位置,如何加入或创建家庭组
1 打开网络和共享中心,点击连接上网的哪一个网络,点击把公用网络改为家庭网络 2 依次执行下一步 3 如果是加入一个家庭组,则输入家庭组的密码,否则将得到一个家庭组的密码 4 加入成功 ...
- 服务器变量 超级全局数组$_SERVER (附加超简单表单与html5表单属性)
001.html <html> <head><title>user log</title> <meta http-equiv="cont ...
- Spark修炼之道——Spark学习路线、课程大纲
课程内容 Spark修炼之道(基础篇)--Linux基础(15讲).Akka分布式编程(8讲) Spark修炼之道(进阶篇)--Spark入门到精通(30讲) Spark修炼之道(实战篇)--Spar ...
- kindeditor 图片上传插件
富文本编辑器,kindeditor是比较好用的一款.需要的功能都有,文档.demo也详细.有什么功能去官网看一眼就好. 官网:http://kindeditor.net/ 一些好用的如图片上传,kin ...
- LR打不开浏览器的解决方法
很久没用LoadRunner了,今天想复习一下,免得技能生疏,安装了一个LR11,跑一下,竟然打不开IE浏览器: 这时肯定是靠谷哥跟度娘的,经过一轮搜索,可以解决打开IE了,但录制不了解决,又 ...
- UML for mac
今年苹果公司推出的iPhone4和iPad继续大获成功,国内想在苹果的平台下开发软件赚钱的开发人员越来越多.那么,在苹果的平台下开发软件有哪些UML建模工具可用呢?虽然不如Windows平台下那么多的 ...
- <译>Spark Sreaming 编程指南
Spark Streaming 编程指南 Overview A Quick Example Basic Concepts Linking Initializing StreamingContext D ...