preface

In addition to providing distributed locks, Redisson provides additional synchronization components, Semaphore and CountDownLatch.

Semaphore

This means that in a distributed scenario, there are only three credentials, which means that there are only three threads executing business at the same time.

Set the credentials

Parameter list:

  1. KEYS[1] : semaphore
  2. KEYS [2] : redisson_sc: {semaphore}
  3. ARGV[1] : certificate number 3

This Lua script is relatively simple, setting the value of a key to 3.

To obtain credentials

Parameter list:

  1. KEYS[1] : semaphore
  2. ARGV[1] : Number of credentials to obtain, default 1

This lua script is:

  1. Gets the value of key Semaphore
  2. If the value is greater than or equal to 1 (the number of credentials to obtain), the value is decremented
  3. Returns 1 on success and 0 on failure

If the credential is successfully obtained, it returns directly. If no credential is obtained, the spin waits.

Release the documents

The value of Redis key can be incremented directly by releasing the certificate.

CountDownLatch

The output is as follows:

Source code analysis

Set the number of latches

It’s all pretty much the same.

Reduce the number of bolts

It’s decrementing this value.

Latch.await () spins to get the value of the latch until it is zero, and then executes further.

conclusion

Redisson basically implements distributed Semaphore and CountDownLatch by simply maintaining a common variable in Redis and then atomic updates.

Related to recommend

  • Redisson distributed lock source code 10: read and write lock
  • Redisson distributed lock source code 09: RedLock RedLock story
  • 08: MultiLock and lock release