zookeeper读书笔记十二 zookeeper应用之实现分布式锁

  • client想要获得锁需要执行以下步骤
  1. Call create( ) with a pathname of "locknode/guid-lock-" and the sequence and ephemeral flags set. The guid is needed in case the create() result is missed. See the note below.
  2. Call getChildren( ) on the lock node without setting the watch flag (this is important to avoid the herd effect).
  3. If the pathname created in step 1 has the lowest sequence number suffix, the client has the lock and the client exits the protocol.
  4. The client calls exists( ) with the watch flag set on the path in the lock directory with the next lowest sequence number.
  5. if exists( ) returns null, go to step 2. Otherwise, wait for a notification for the pathname from the previous step before going to step 2.

zookeeper读书笔记十二 zookeeper应用之实现分布式锁

  • 实现分布式读写锁

获取读锁的关键判断,只要当前子节点前没有写锁的子节点,就可以获得读锁。否则要等前面的写锁对应的节点删除才能获取读锁。

获取写锁的关键判断,只要当前子节点前面有任何子节点,都不能获取锁,要等前面的子节点都删除,才能获取锁。

Obtaining a read lock: Obtaining a write lock:
1. Call create( ) to create a node with pathname "guid-/read-". This is the lock node use later in the protocol. Make sure to set both the sequence and ephemeral flags. 1. Call create( ) to create a node with pathname "guid-/write-". This is the lock node spoken of later in the protocol. Make sure to set both sequence and ephemeral flags.
2. Call getChildren( ) on the lock node without setting the watch flag - this is important, as it avoids the herd effect. 2. Call getChildren( ) on the lock node without setting the watch flag - this is important, as it avoids the herd effect.
3. If there are no children with a pathname starting with "write-" and having a lower sequence number than the node created in step 1, the client has the lock and can exit the protocol. 3. If there are no children with a lower sequence number than the node created in step 1, the client has the lock and the client exits the protocol.
4. Otherwise, call exists( ), with watch flag, set on the node in lock directory with pathname staring with "write-" having the next lowest sequence number. 4. Call exists( ), with watch flag set, on the node with the pathname that has the next lowest sequence number.
5. If exists( ) returns false, goto step 2. 5. If exists( ) returns false, goto step 2. Otherwise, wait for a notification for the pathname from the previous step before going to step 2.
6. Otherwise, wait for a notification for the pathname from the previous step before going to step 2