zookeeper

zookeeper

zookeeper是啥

apache的开源的分布式协调服务器
ZooKeeper is a centralized service for maintaining configuration information, naming, providing distributed synchronization, and providing group services. All of these kinds of services are used in some form or another by distributed applications.
Zookeeper从设计模式角度来理解:是一个基于观察者模式设计的分布式服务管理框架,它负责存储和管理大家都关心的数据,然后接受观察者的注册,一旦这些数据的状态发生变化,Zookeeper就将负责通知已经在Zookeeper上注册的那些观察者做出相应的反应。
zookeeper = 文件系统 + 通知机制
Zookeeper 作为一个分布式的服务框架,主要用来解决分布式集群中应用系统的一致性问题,它能提供基于类似于文件系统的目录节点树方式的数据存储,但是 Zookeeper 并不是用来专门存储数据的,它的作用主要是用来维护和监控你存储的数据的状态变化。通过监控这些数据状态的变化,从而可以达到基于数据的集群管理
其一致性是通过基于 Paxos 算法的 ZAB 协议完成的。其主要功能包括:配置维护、分布式同步、集群管理、分布式事务等。

  1. 分布式服务器
  2. 高可靠 -》集群模式
  3. 高性能、低延迟-》内存,适用于读多写少,写的数据少

安装

windows下单机安装

下载

官网
下载地址
https://www.apache.org/dyn/closer.lua/zookeeper/zookeeper-3.6.1/apache-zookeeper-3.6.1-bin.tar.gz

配置

解压后,手动创建datalog目录
解压后的目录
其中
bin: 脚本文件
conf: 配置文件

拷贝conf/zoo_sample.cfgconf/zoo.cfg,修改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=D:\\software\\apache-zookeeper-3.6.1-bin\\data
dataLogDir=D:\\software\\apache-zookeeper-3.6.1-bin\\log
# the port at which the clients will connect
clientPort=2181
# 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.
#
# http://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.httpPort=7000
#metricsProvider.exportJvmInfo=true
启动

双击bin/zkServer.cmd启动服务器
双击bin/zkCli.cmd启动客户端

windows下集群安装

将解压后的文件复制三分

分别重命名为**-2887、**-2888、**-2889
在这里插入图片描述

修改配置

apache-zookeeper-3.6.1-bin-2887为例,修改dataDir、dataLogDir、clientPort

# 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=D:\\software\\apache-zookeeper-3.6.1-bin-2887\\data
dataLogDir=D:\\software\\apache-zookeeper-3.6.1-bin-2887\\log
# the port at which the clients will connect
clientPort=2187
## *****************************************************
# 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.
#
# http://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.httpPort=7000
#metricsProvider.exportJvmInfo=true
#############cluster############
server.7=127.0.0.1:2887:3887
server.8=127.0.0.1:2888:3888
server.9=127.0.0.1:2889:3889

dataDir目录下创建myid文件内容为7

cat > myid <<EOF
7
EOF

对应修改其他的两个实例

启动

分别双击bin/zkServer.cmd启动服务器就可以了

zookeeper的原理

数据结构

类似unix的文件系统,每个节点称为Znode,它可以存储小于1M大小的数据

通知机制

客户端创建zookeeper客户端,他会创建两个线程:一个同于网络连接通信(connect);一个用于监听路径或者数据的变化(listener)

应用场景

分布式锁

可以实现可重入的公平锁

命名服务

分布式ID

配置管理【发布/订阅】

配置中心

选举master

其实很简单,所谓的选举master就是从多个实例中选择一个实例,把它当做master
方法1:使用mysql,向mysql中插入一条相同主键的记录,这有一个实例可以成功插入,其他实例会报错,那么这个实例就是master
缺点就是master挂了就不行了
方法2:使用zk,各个实例向zk创建节点,只有一个节点会成功,这个节点就是master,其他节点通过watch这个节点,如果这个节点挂了,就说明master挂了,其他节点重新选举master

集群管理

集群监控和管理
集群有多少台节点
节点的动态上下线
节点的运行时状态,节点的agent向zk写数据
节点注册和发现

软负载均衡

让节点访问最少的负责新客户的请求

DNS服务
乐观锁

使用数据的version,只有数据的当前版本和我们想要的版本一样才会成功
zk的stat有三个version
cversion:子节点
dataVersion:数据
aclVersion:权限

分布式队列

FIFO:和分布式锁类似,瞬时顺序节点,监听前一个节点,FIFO
Barrier:是FIFO的增强,只有几个节点都完成才乡下进行。
方案是:在zk父节点创建节点个数N,各个实例创建父节点的子节点,同时watch子节点个数的变化,一旦子节点的个数达到N,就乡下执行。

client基本操作

[zk: localhost:2181(CONNECTED) 0] help
ZooKeeper -server host:port -client-configuration properties-file cmd args
        addWatch [-m mode] path # optional mode is one of [PERSISTENT, PERSISTENT_RECURSIVE] - default is PERSISTENT_RECURSIVE
        addauth scheme auth
        close
        config [-c] [-w] [-s]
        connect host:port
        create [-s] [-e] [-c] [-t ttl] path [data] [acl]
        delete [-v version] path
        deleteall path [-b batch size]
        delquota [-n|-b] path
        get [-s] [-w] path
        getAcl [-s] path
        getAllChildrenNumber path
        getEphemerals path
        history
        listquota path
        ls [-s] [-w] [-R] path
        printwatches on|off
        quit
        reconfig [-s] [-v version] [[-file path] | [-members serverID=host:port1:port2;port3[,...]*]] | [-add serverId=host:port1:port2;port3[,...]]*
[-remove serverId[,...]*]
        redo cmdno
        removewatches path [-c|-d|-a] [-l]
        set [-s] [-v version] path data
        setAcl [-s] [-v version] [-R] path acl
        setquota -n|-b val path
        stat [-w] path
        sync path
        version
Command not found: Command not found help
[zk: localhost:2181(CONNECTED) 1]
[zk: localhost:2181(CONNECTED) 1]
[zk: localhost:2181(CONNECTED) 1]
version
[zk: localhost:2181(CONNECTED) 9] version
ZooKeeper CLI version: 3.6.1--104dcb3e3fb464b30c5186d229e00af9f332524b, built on 04/21/2020 15:01 GMT
[zk: localhost:2181(CONNECTED) 10]
crud

create
get ls
set
delete

stat结构体
[zk: localhost:2181(CONNECTED) 13] get -s /tom
lixi-03
cZxid = 0x4         # 创建的事务ID
ctime = Thu Feb 11 10:13:30 CST 2021  ## 创建的时间
mZxid = 0x7         # 修改的事务ID
mtime = Thu Feb 11 10:21:38 CST 2021  ## 修改的时间
pZxid = 0x9			# 子Znode节点最后更新的cZxid 
cversion = 2        # 子Znode节点变化version
dataVersion = 2     # 当前Znode节点数据变化version
aclVersion = 0      # znode 访问控制列表的变化version
ephemeralOwner = 0x0 # 临时节点所属的客户端
dataLength = 7       #zonde节点的数据长度
numChildren = 2      # 子znode的数量
[zk: localhost:2181(CONNECTED) 14]
[zk: localhost:2181(CONNECTED) 16] get -s /tom/anna
anna
cZxid = 0x9
ctime = Thu Feb 11 10:23:51 CST 2021
mZxid = 0x9
mtime = Thu Feb 11 10:23:51 CST 2021
pZxid = 0x9
cversion = 0
dataVersion = 0
aclVersion = 0
ephemeralOwner = 0x100001ee42e0001
dataLength = 4
numChildren = 0
[zk: localhost:2181(CONNECTED) 17]

zookeeper节点的权限控制

类似于unix的文件控制属性在这里插入图片描述
其中授权策略有4个:

  • world : 默认方式,所有用户都可无条件访问。
  • auth :不使用任何 id,代表任何已认证的用户。
  • digest :用户名:密码认证方式: username:password
  • ip : 对指定 ip 进行限制。
    权限:crwda
    create: 能创建子节点
    read:读节点和列出子节点
    write:设置、更新节点
    delete:能删除子节点
    ADMIN : 能设置节点 ACL 的权限

zookeeper的介绍

一个分布式协调服务,用于命名服务【ID】、配置中心、集群管理【节点注册和发现】等,也可以用来做分布式锁,比redis实现更加直观同时因为他的通知机制也比redis更好一点。同时他也是hadoopc生态中的一员,kafka集群必须依赖的组件,zookeeper集群提供的AP,选用的集群最好是技术台,他讲数据存储在内存中,节点可以存储1M大小的数据,但是我们不应该把它用于存储,它适用于读大于写的应用。
在zookeeper底层只有两个功能:1:存储和获取用户存储的数据,2:数据节点的监控。
它有4中节点类型:持久节点、临时节点、持久顺序节点、临时顺序节点

节点的数据有两部分组成:data和stat
zookeeper的集群有三种角色:leader、follower、observer
角色说明
Leader为客户端提供读和写的服务,负责投票的发起和决议,更新系统状态。
Follower为客户端提供读服务,如果是写服务则转发给 Leader。在选举过程中参与投票。
Observer为客户端提供读服务器,如果是写服务则转发给 Leader。不参与选举过程中的投票,也不参与“过半写成功”策略。在不影响写性能的情况下提升集群的读性能。此角色于 ZooKeeper3.3 系列新增的角色。

observer节点不参与节点的选举,在不影响写性能的情况下提升集群的读性能。

选举过程
  1. Leader election(选举阶段):节点在一开始都处于选举阶段,只要有一个节点得到超半数节点的票数,它就可以当选准 leader。
  2. Discovery(发现阶段) :在这个阶段,followers 跟准 leader 进行通信,同步 followers 最近接收的事务提议。
  3. Synchronization(同步阶段) :同步阶段主要是利用 leader 前一阶段获得的最新提议历史,同步集群中所有的副本。同步完成之后
    准 leader 才会成为真正的 leader。
  4. Broadcast(广播阶段) :到了这个阶段,ZooKeeper 集群才能正式对外提供事务服务,并且 leader 可以进行消息广播。同时如果有新的节点加入,还需要对新节点进行同步。
ZooKeeper 集群中的服务器状态
  • LOOKING :寻找 Leader。
  • LEADING :Leader 状态,对应的节点为 Leader。
  • FOLLOWING :Follower 状态,对应的节点为 Follower。
  • OBSERVING :Observer 状态,对应节点为 Observer,该节点不参与 Leader 选举。
    ZooKeeper 集群为啥最好奇数台?一半以上何必增加那一个不必要的 ZooKeeper 呢?
选举步骤
启动时期

每个节点不知道他节点的状态,都是LOOKING状态,并且都投票给自己
票据(SID,ZXID)
比较步骤:
ZXID 大的就是自己要投票的,
ZXID 小的还坚持自己的投票
ZXID一致,SID大的是自己要投票的
ZXID一致,SID小或等于的,还坚持自己的投票
改变自己的状态:LEADING、FOLLOWING

运行时期

改变状态为LOOKING
发出投票
接受投票
处理投票
统计投票
改变状态

zk的日志

格式是log.zxid 大小都是64M,里面有zk的磁盘预分配策略

在linux上可以使用

java -classpath .:slf4j-api-1.7.25.jar:zookeeper-3.4.14.jar org.apache.zookeeper.server.LogFormatter log.1100000001

windows上使用

D:\software\apache-zookeeper-3.6.1-bin\lib>java -cp "D:\software\apache-zookeeper-3.6.1-bin\lib\*" org.apache.zookeeper.server.LogFormatter  log.38
ZooKeeper Transactional Log File with dbid 0 txnlog format version 2
log4j:WARN No appenders could be found for logger (org.apache.zookeeper.server.ZooKeeperServer).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
21-2-12 上午08时49分20秒 session 0x100000b03a20000 cxid 0x0 zxid 0x38 createSession 30000
 2,23500875606

21-2-12 上午08时49分35秒 session 0x100000b03a20000 cxid 0x2 zxid 0x39 error -101
 null
21-2-12 上午08时49分54秒 session 0x100000b03a20000 cxid 0x3 zxid 0x3a error -101
 null
21-2-12 上午08时50分42秒 session 0x100000b03a20000 cxid 0x4 zxid 0x3b create '/globalids,#696473,v{s{31,s{'world,'anyone}}},F,5
 2,22893744820

21-2-12 上午08时51分01秒 session 0x100000b03a20000 cxid 0x5 zxid 0x3c create '/globalids/id0000000000,#6f,v{s{31,s{'world,'anyone}}},T,1
 2,25313472364

21-2-12 上午08时51分18秒 session 0x100000b03a20000 cxid 0x6 zxid 0x3d create '/globalids/id0000000001,#303030,v{s{31,s{'world,'anyone}}},T,2
 2,26233747216

chroot

zk的一种命令空间隔离的概念
比如设置为/app/v1
那么客户端所有的操作都是相对于这个路径来说的

zookeeper里面的采用的是ZAB【zookeeper atomic boradcast 原子广播】协议【paxos协议的定制】

ZAB 协议包括两种基本的模式,分别是
  • 崩溃恢复 :当整个服务框架在启动过程中,或是当 Leader 服务器出现网络中断、崩溃退出与重启等异常情况时,ZAB 协议就会进入恢复模式并选举产生新的Leader服务器。当选举产生了新的 Leader 服务器,同时集群中已经有过半的机器与该Leader服务器完成了状态同步之后,ZAB协议就会退出恢复模式。其中,所谓的状态同步是指数据同步,用来保证集群中存在过半的机器能够和Leader服务器的数据状态保持一致
  • 消息广播当集群中已经有过半的Follower服务器完成了和Leader服务器的状态同步,那么整个服务框架就可以进入消息广播模式了。 当一台同样遵守ZAB协议的服务器启动后加入到集群中时,如果此时集群中已经存在一个Leader服务器在负责进行消息广播,那么新加入的服务器就会自觉地进入数据恢复模式:找到Leader所在的服务器,并与其进行数据同步,然后一起参与到消息广播流程中去。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值