简介
最近做的项目用的是zookeeper+kafka,大致学习了下zookeeper。像Spring有IOC和AOP一样,zookeeper的核心主要是文件结构和监听机制
安装
Zookeeper 的安装还是比较简单的,注意安装目录不要有中文和空格即可
附上安装包
启动
Windows系统双击zkServer.cmd启动
启动闪退的话,右键编辑zkServer.cmd,在末尾加上pause
保存后继续双击运行,一般会有报错产生,没有报错说明正常启动
提示找不到配置文件,需要在config中修改配置文件
将zoo_sample.cfg文件复制一份重命名为zoo.cfg,右键编辑
这样双击zkServer.cmd就可以正常启动了
常用操作
双击zkCli.cmd启动客户端
1.ls 查看指定路径下的节点
2.create:创建一个节点
创建内容为test的/newnode节点
3.get:显示指定路径下节点的信息
4.set:设置节点的内容
可以和get的节点对比看下
5.delete:删除一个节点
java案例
熟悉了zookeeper的常用操作后,我们基于zookeeper的文件结构和监听机制来用java模拟下服务节点的动态上下线。熟悉SpringCloud的小伙伴可能清楚,我们微服务架构下的EurekaService会在单独服务启动成功后,自动在注册中心显示,服务下线后会自动在注册中心下线,下面代码就是模拟了这种服务的发现与注销
<dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.6</version> </dependency>
服务端
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import java.util.ArrayList;
import java.util.List;
public class ZookeeperServer {
static ZooKeeper zooKeeper;
public static void main(String[] args) {
try {
String connectString = "localhost:2181";
int sessionTimeout = 5000;
zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
public void process(WatchedEvent watchedEvent) {
String path = "/servers";
try {
List<String> childrens = zooKeeper.getChildren(path, true);
List<String> hosts = new ArrayList<String>();
for (String child : childrens) {
byte[] dataByte = zooKeeper.getData(path+"/"+child, false, null);
hosts.add(new String(dataByte));
}
System.out.println("启动服务:"+hosts);
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread.sleep(Long.MAX_VALUE);
} catch (Exception e) {
e.printStackTrace();
}
}
}
客户端
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;
import org.apache.zookeeper.ZooKeeper;
public class ZookeeperClient {
static ZooKeeper zooKeeper;
public static void main(String[] args) {
try {
String connectString = "localhost:2181";
int sessionTimeout = 5000;
zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
public void process(WatchedEvent watchedEvent) {
// 启动userService服务
String serviceName = "userService";
// 设置服务目录
String path = "/servers/node";
try {
zooKeeper.create(path, serviceName.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread.sleep(Long.MAX_VALUE);
} catch (Exception e) {
e.printStackTrace();
}
}
}
先通过zkCli.cmd创建servers节点
create /servers ""
启动ZookeeperServer监听服务,然后启动ZookeeperClient的用户服务,还可以通过zkCli.cmd创建其他节点,打印日志如下
其他
好了今天的zookeeper入门就到这里了,大家有什么问题和建议可以一起沟通下,不想安装环境的可以找我连向日葵练习:)