这几天利用好好工作摸鱼的时间梳理了一遍 Zookeeper 相关的内容。今天就给大家分享一下我这几天摸鱼的成果,本文主要内容包括 Zookeeper的配置安装、基本命令和ava API 的使用以及Zookeeper内部数据的存储方式以及Znode的特点、Watch 机制的详细介绍,最后聊了一下Zookeeper的应用场景,通篇文章都是理论+图解+代码实操,坚持看完相信你肯定会有所收获。
1、安装和配置
1.1、首先下载安装包
#下载安装包
wget https://dlcdn.apache.org/zookeeper/zookeeper-3.9.2/apache-zookeeper-3.9.2-bin.tar.gz
## 解压软件包
tar zxvf apache-zookeeper-3.9.2-bin.tar.gz
## 重命名后放到指定目录下
mv apache-zookeeper-3.9.2-bin zookeeper-3.9.2
mv zookeeper-3.9.2 /usr/local/
这里按照习惯我放到了/usr/local 目录下了。
1.2、修改配置
官方文档连接: ZooKeeper: Because Coordinating Distributed Systems is a Zoo
这里我们参照官方文档上的说明 新建一个数据目录,然后修改zoo.cfg配置文件
这里解释一下几个参数:
tickTime: ZooKeeper使用的基本时间单位(毫秒)。它用于执行心跳,最小会话超时将是tickTime的两倍。
dataDir: 存储内存中数据快照的路径
clientPort: 监听客户端连接的端口 这里我是将原来的 文件复制了一份然后在原来的基础上修改,内容如下
[root@VM-4-9-centos zookeeper-3.9.2]# cat conf/zoo.cfg
# The number of milliseconds of each tick
tickTime=2000
# The number of ticks that the initial
# synchronization phase can take
initLimit=10
# The number of ticks that can pass between
# sending a request and getting an acknowledgement
syncLimit=5
# the directory where the snapshot is stored.
# do not use /tmp for storage, /tmp here is just
# example sakes.
dataDir=/opt/zookeeper/data
# the port at which the clients will connect
clientPort=9009
# the maximum number of client connections.
# increase this if you need to handle more clients
#maxClientCnxns=60
#
# Be sure to read the maintenance section of the
# administrator guide before turning on autopurge.
#
# https://zookeeper.apache.org/doc/current/zookeeperAdmin.html#sc_maintenance
#
# The number of snapshots to retain in dataDir
#autopurge.snapRetainCount=3
# Purge task interval in hours
# Set to "0" to disable auto purge feature
#autopurge.purgeInterval=1
## Metrics Providers
#
# https://prometheus.io Metrics Exporter
#metricsProvider.className=org.apache.zookeeper.metrics.prometheus.PrometheusMetricsProvider
#metricsProvider.httpHost=0.0.0.0
#metricsProvider.httpPort=7000
#metricsProvider.exportJvmInfo=true
keeper.jute.maxbuffer=104857600
[root@VM-4-9-centos zookeeper-3.9.2]#
需要注意的是 这里我将自己的端口改成了9009 大家可以自己设置
1.3、启动服务
启动服务和查看服务状态的命令主要有以下几个
# 启动 ZooKeeper 服务
./zkServer.sh start
# 查看 ZooKeeper 服务状态
./zkServer.sh status
# 停止 ZooKeeper 服务
./zkServer.sh stop
# 重启 ZooKeeper 服务
./zkServer.sh restart
命令实操:
[root@localhost zookeeper-3.9.2]# ./bin/zkServer.sh start
ZooKeeper JMX enabled by default
Using config: /usr/local/zookeeper-3.9.2/bin/../conf/zoo.cfg
Starting zookeeper ... STARTED
[root@localhost zookeeper-3.9.2]# ./bin/zkServer.sh status
ZooKeeper JMX enabled by default
Using config: /usr/local/zookeeper-3.9.2/bin/../conf/zoo.cfg
Client port found: 2181. Client address: localhost. Client SSL: false.
Mode: standalone
[root@localhost zookeeper-3.9.2]#
2、客户端主要命令
2.1、连接客户端
# 格式 -server ip:port
/zkCli.sh -server 127.0.0.1:2181
# 断开连接
quit
连接成功的效果如下
2.2、CRUD命令
对于Zookeeper常用的命令 我梳理成了下面的一张表格,主要就以下几个
命令 | 释义 |
c |