zookeeper 临时节点技术细节备注

临时节点多久会被删除

zookeeper的临时节点顾名思义是临时的,也就是说在一个连接session有效期内临时节点是活跃的,当连接断开后,session会自然的过期,session中过期了那么临时节点就会被删除

ZooKeeper also has the notion of ephemeral nodes. These znodes exists as long as the session that created the znode is active. When the session ends the znode is deleted.

那么session的时间默认是多少呢,答案是2xtickTime到20xtickTime之间

Ticks When using multi-server ZooKeeper, servers use ticks to define timing of events such as status uploads, session timeouts, connection timeouts between peers, etc. The tick time is only indirectly exposed through the minimum session timeout (2 times the tick time); if a client requests a session timeout less than the minimum session timeout, the server will tell the client that the session timeout is actually the minimum session timeout.

the basic time unit in milliseconds used by ZooKeeper. It is used to do heartbeats and the minimum session timeout will be twice the tickTime.

One of the parameters to the ZooKeeper client library call to create a ZooKeeper session is the session timeout in milliseconds. The client sends a requested timeout, the server responds with the timeout that it can give the client. The current implementation requires that the timeout be a minimum of 2 times the tickTime (as set in the server configuration) and a maximum of 20 times the tickTime. The ZooKeeper client API allows access to the negotiated timeout.

所以不是连接断开就会导致临时节点马上被删除,还需要等待一点点的时间,这意味这session时间内我们还可以救活一个临时节点,当一个连接被意外关闭或者网络原因断开连接后.

我们怎么救活一个临时节点?

我们可以马上有连上了在更新下这个临时节点,

# 创建一个临时节点
[zk: localhost:2181(CONNECTED) 4] create -e /e1 thinktik
Created /e1
# 断开连接然后重新连接,这时查询这个节点还是可以的
[zk: localhost:2181(CONNECTED) 5] get /e1
thinktik
# 过一段时间后,这个节点会消失
[zk: localhost:2181(CONNECTED) 6] 2021-02-15 22:36:26,256 [myid:] - ERROR [main:ServiceUtils@42] - Exiting JVM with code 0

重新连接并不能救活临时节点,因为2次连接的session不一样,我们继续测试

# 创建一个临时节点
[zk: localhost:2181(CONNECTED) 4] create -e /e1 thinktik
Created /e1
# 断开连接然后重新连接,这时查询这个节点还是可以的
[zk: localhost:2181(CONNECTED) 0] get /e1
thinktik
# 重新更新下这个临时节点,就行了
[zk: localhost:2181(CONNECTED) 1] set /e1 think

更多有关的资料请看:session

警告: 这个知识点其实没有实际价值,算是很冷门的小细节,也千万不要把这个细节用到生产环境中作为某种业务的逻辑实现来使用

参考:

临时节点可以有子节点吗

不行,临时节点不可以有子节点

Because of this behavior ephemeral znodes are not allowed to have children.

我们可以这样验证

[zk: localhost:2181(CONNECTED) 17] create -e /e1 thinktik
Created /e1
# 报错,强调不能给临时节点创建子节点
[zk: localhost:2181(CONNECTED) 18] create -e /e1/se1
Ephemerals cannot have children: /e1/se1

本文原创链接: zookeeper 临时节点技术细节备注

你可能感兴趣的:(zookeeper)