Distributed caching, can solve the single server memory can not be unlimited expansion of the bottleneck. In the application of distributed caching, multiple client contention issues are encountered. This time, need to use a distributed lock, the client has access to the lock to operate permissions.
Memcached and Redis are common distributed cache-building schemes, and the following are examples of implementation methods based on Memcached and Redis distributed locks.
Memcached Distributed Locks
Memcached can use the add command, which is added only if the key does not exist , or is not processed. Memcached All commands are atomic, and then add the same key, only one will succeed.
Using this principle, you can first define a lock Lockkey, add success that is to get the lock. and set the [ expired timeout ] time to ensure that after the downtime , it will not deadlock .
After the concrete operation, determine if this operation has timed out. If the timeout is not removed, the lock is removed if the timeout is not timed out.
Pseudo code:
1 if (MC. ADD ("Lockkey", "Value", ExpiredTime))
2 {
3 //Get lock
4 try
5 {
6 //do Business function
7
8 //Check timeout
9 if (! Checkedtimeout ())
a MC. Delete ("Lockkey"); catch (Exception e) in MC. Delete ("Lockkey");
{ }
Redis Distributed Locks
Redis does not have the add command, but there is setnx(SET if not eXists) if the given key already exists, then SETNX does not do any action. The setting succeeds and returns 1. Setting failed, returns 0.
The SETNX command cannot set an expiration time, and you need to use the EXPIRE command to set the expiration time.
Pseudo code:
1 2 3 4 5 6 7 8 9 A-list of |