etcdctl查看分布式锁状态

2022-09-27  本文已影响0人  Ballpenww

etcd提供分布式锁能力,经常会出现获取锁超时报错,当然这个在逻辑上是正常,一个进程持有锁在没有释放期间,其他进程不能获取锁。但从运维测如何确认这个锁是否工作正常呢?

首先etcd实现分布式锁的原理

分布式锁要求

etcd实现原理

etcd的几种特殊的机制都可以作为分布式锁的基础。etcd的键值对可以作为锁的本体,锁的创建与删除对应键值对的创建与删除。etcd的分布式一致性以及高可用可以保证锁的高可用性

分布式锁的操作

etcdctl查看锁状态

了解了etcd实现分布式锁的原理,可以支持etcd中分布式锁的结构是:lock_name/lease_id

# etcdctl lock <lockname> [exec-command arg1 arg2 ...]
# exec-cmd 是说执行完改名了后释放锁;如果不加命令,会一直持有锁
# --ttl=10  timeout for session 
# 从命令介绍看,默认10s的lease租期
$ ETCDCTL_API=3 etcdctl lock a1_lock sleep 5  【等待5s都释放锁】
# 通过prefix参数就能监听a1_lock的锁状态
$ ETCDCTL_API=3 etcdctl watch a1_lock --prefix 
PUT
a1_lock/3668830c8895c46b

DELETE
a1_lock/3668830c8895c46b
$ time etcdctl lock a2_lock
a2_lock/3668830c889630c7

^C   # kill 命令
real    0m15.283s
user    0m0.009s
sys 0m0.023s

查看终端

$ while [[ 1 > 0 ]]; do etcdctl lease timetolive 3668830c889630c7; sleep 1; done
lease 3668830c889630c7 granted with TTL(10s), remaining(8s)
lease 3668830c889630c7 granted with TTL(10s), remaining(7s)
lease 3668830c889630c7 granted with TTL(10s), remaining(9s)
lease 3668830c889630c7 granted with TTL(10s), remaining(8s)
lease 3668830c889630c7 granted with TTL(10s), remaining(7s)  # 持有进程异常点,
lease 3668830c889630c7 granted with TTL(10s), remaining(9s)
lease 3668830c889630c7 granted with TTL(10s), remaining(8s)
lease 3668830c889630c7 granted with TTL(10s), remaining(7s)
lease 3668830c889630c7 granted with TTL(10s), remaining(6s)
lease 3668830c889630c7 granted with TTL(10s), remaining(5s)
lease 3668830c889630c7 granted with TTL(10s), remaining(4s)
lease 3668830c889630c7 granted with TTL(10s), remaining(3s)
lease 3668830c889630c7 granted with TTL(10s), remaining(2s)
lease 3668830c889630c7 granted with TTL(10s), remaining(1s)
lease 3668830c889630c7 granted with TTL(10s), remaining(0s)
lease 3668830c889630c7 granted with TTL(10s), remaining(0s)
lease 3668830c889630c7 already expired     # 释放锁
lease 3668830c889630c7 already expired

谢各位,如对您有帮助请点赞!

上一篇 下一篇

猜你喜欢

热点阅读