ZooKeeper: A Distributed Coordination Service for Distributed Applications。
ZooKeeper is a centralized service for maintaining configuration information, naming, providing distributed synchronization, and providing group services.
zookeeper是用于分布式中一致性处理
的框架。保证在分布式环境下数据的最终一致
。
可以用于维护配置信息、名字服务,提供分布式同步以及集群管理。
1、可以为客户端管理少量数据
2、可以为客户端监听指定数据节点的状态并在数据节点发生变化时,通知客户端
配置文件
# ./zookeeper/conf/zoo.cfg
...
clientPort=2181 // 2181=>客户端连接端口
dataDir=/opt/zookeeper/data
server.1=hadoop01:2888:3888 // 2888=>leader,follower通信
server.2=hadoop04:2888:3888 // 3888=>投票端口
server.3=hadoop05:2888:3888
生成对应文件: ./zookeeper/data/myid
zookeeper命令
./bin/zkServer.sh start //启动zkServer 进程名 => QuorumPeerMain
./bin/zkServer.sh status
./bin/zkServer.sh stop
./bin/zkCli.sh -server hadoop01:2181 //启动客户端
zookeeper提供的原语服务、和命令:
服务 | 命令 |
---|---|
帮助 | help |
创建节点persistent | create /test "hello zk" |
创建临时节点ephemeral | create -e /test "hello zk" |
创建顺序节点 | create -s /test "hello zk" |
删除节点 | delete /test |
更新节点 | set /test "change" |
获取节点信息 | ls /test get /test |
权限控制 | 。。。 |
事件监听 | get /test watch |
Conditional updates and watches
ZooKeeper支持watches的概念。客户端可以在 Znode 上设置监听
。当 Znode 发生变化时,监听会被触发并移除。触发监听时,客户端会收到一个数据包告知 Znode 发生变更。如果客户端与其中一个 ZooKeeper 服务器之间的连接中断,则客户端将收到本地通知。
Guarantees
ZooKeeper is very fast and very simple.
- Sequential Consistency - Updates from a client will be applied in the order that they were sent.
- Atomicity - Updates either succeed or fail. No partial results.
- Single System Image - A client will see the same view of the service regardless of the server that it connects to.
- Reliability - Once an update has been applied, it will persist from that time forward until a client overwrites the update.
- Timeliness - The clients view of the system is guaranteed to be up-to-date within a certain time bound.
• 顺序一致性:客户端的更新将按顺序应用。
• 原子性:更新要么成功要么失败,没有其他结果
• 单一视图:无论客户端连接到哪个服务,所看到的环境都是一样的
• 可靠性:开始更新后,它将从该时间开始,一直到客户端覆盖更新
• 及时性:系统的客户视图保证在特定时间范围内是最新的。
zookeeper的选举机制->GO
1. 服务器状态
服务器具有四种状态,分别是LOOKING、FOLLOWING、LEADING、OBSERVING。
LOOKING:寻找Leader状态。当服务器处于该状态时,它会认为当前集群中没有Leader,因此需要进入Leader选举状态。
FOLLOWING:跟随者状态。表明当前服务器角色是Follower。
LEADING:领导者状态。表明当前服务器角色是Leader。
OBSERVING:观察者状态。表明当前服务器角色是Observer。
Leader选举是保证分布式数据一致性的关键所在。当Zookeeper集群中的一台服务器出现以下两种情况之一时,需要进入Leader选举。
(1) 服务器初始化启动。
(2) 服务器运行期间无法和Leader保持连接。
1. 服务器启动时期的Leader选举
(1) 每个Server发出一个投票。(myid, ZXID)
(2) 接受来自各个服务器的投票。
(3) 处理投票。针对每一个投票,服务器都需要将别人的投票和自己的投票进行PK,PK规则如下
- 优先检查ZXID。ZXID比较大的服务器优先作为Leader。
- 如果ZXID相同,那么就比较myid。myid较大的服务器作为Leader服务器。
(4) 统计投票。
(5) 改变服务器状态。
面试:
有没有用过zk
zk的选举机制是怎样的
zk一致性原理
zk挂了怎么办
分布式锁的实现方式,zk实现和Redis实现的比较
zookeeper应用场景
服务器压力一样,连接过来怎么保证负载均衡,用zookeeper
了解分布式事务嘛,了解,但是没有大型项目的实战,讲JTA,用MQ,zookeeper保障一致性
介绍下,zookeeper持久化节点和临时节点,注册中心怎么与服务方保持心跳的
应用
1、服务器上下线的的感知
2、配置文件的同步