Practical chapter-17. Distributed lock-Redisson function introduction_bilibili_bilibili
1. Problems that still exist
It is very troublesome to implement directly, so we need to learn from existing frameworks.
2.Redisson usage
3.Redisson reentrant principle
When acquiring the lock, check whether the applying thread and the thread holding the lock are consistent, and then calculate the number of times the thread has acquired the lock. When a method is completed, the count is reduced by one, and the count can only be unlocked when it reaches 0.
The hash structure is used for counting, but hash cannot set the mutex lock and expiration time at the same time like string, so it must be set separately.
In order to avoid deadlock problems caused by downtime, Lua scripts must be used to ensure the atomicity of the steps of acquiring and releasing locks.
4. Principle of Redisson retry mechanism
Use redis's publish and subscribe to publish messages when the lock is released.
If the attempt to acquire the lock fails, the message will be subscribed, so that others will know when they release the lock.
The waiting time is the maximum waiting time minus the time spent acquiring the lock. If there is no message when the time is up, don't wait.
When there is a message, try to acquire the lock again.
5. Timeout refresh of lock time (watchdog)
ExpirationEntry stores the ID of a thread and its corresponding recursive lock refresh function renewExpiration()
renewExpiration() will automatically reinitialize the time to 30s every 10 seconds to ensure that the lock will never expire, and then call itself recursively to continue the renewal.
The expiration time is added to ensure that the lock has the ability to automatically expire when the service is down. At this time, the Java code (service) will not continue to renew; when the service is not down, the expiration time can be continuously refreshed to ensure that it will not be lost because of business The time is too long and the lock expires.
In short, everything is to ensure that the lock is released by the transaction after the business execution is completed, rather than when the lock expires.
Until the unlock function is called, the lock is released and will not be renewed.
6.Redisson can re-enter, retry, and timeout renewal process summary
Practical combat-21. Distributed lock-Redisson’s multiLock principle_bilibili_bilibili
7.Multilock chain ensures master-slave consistency
The lock is considered successful only if all master nodes successfully obtain the lock, so there is no fear that one node will go down and other threads will take advantage of the opportunity.
8 Thought process
Practical Chapter-22. Flash Kill Optimization-Asynchronous Flash Kill Ideas_bilibili_bilibili