redis locking classification
The locking commands that can be used by redis are INCR, SETNX, SET
The first lock command INCR
The idea of this kind of locking is that if the key does not exist, then the value of the key will be initialized to 0 first, and then the INCR operation will be performed. plus one.
Then when other users perform the INCR operation to add one, if the number returned is greater than 1, it means that the lock is being used.
1、 客户端A请求服务器获取key的值为1表示获取了锁 2、 客户端B也去请求服务器获取key的值为2表示获取锁失败 3、 客户端A执行代码完成,删除锁 4、 客户端B在等待一段时间后在去请求的时候获取key的值为1表示获取锁成功 5、 客户端B执行代码完成,删除锁 $redis->incr($key); $redis->expire($key, $ttl); //设置生成时间为1秒
The second type of lock SETNX
The idea behind this lock is that if the key does not exist, set the key to value
If the key already exists, SETNX does not take any action
1、 客户端A请求服务器设置key的值,如果设置成功就表示加锁成功 2、 客户端B也去请求服务器设置key的值,如果返回失败,那么就代表加锁失败 3、 客户端A执行代码完成,删除锁 4、 客户端B在等待一段时间后在去请求设置key的值,设置成功 5、 客户端B执行代码完成,删除锁 $redis->setNX($key, $value); $redis->expire($key, $ttl);
The third lock SET
The above two methods have a problem, you will find , all need to set the key expiration. So why do we need to set key expiration? If the request execution exits unexpectedly for some reason, causing the lock to be created but not deleted, then the lock will always exist, so that the cache will never be updated in the future. So we need to add an expiration time to the lock to prevent accidents.
But using Expire to set it is not an atomic operation. Therefore, atomicity can also be ensured through transactions, but there are still some problems, so the official cited another one. Using the SET command itself has included the function of setting the expiration time starting from version 2.6.12.
1、 客户端A请求服务器设置key的值,如果设置成功就表示加锁成功 2、 客户端B也去请求服务器设置key的值,如果返回失败,那么就代表加锁失败 3、 客户端A执行代码完成,删除锁 4、 客户端B在等待一段时间后在去请求设置key的值,设置成功 5、 客户端B执行代码完成,删除锁 $redis->set($key, $value, array('nx', 'ex' => $ttl)); //ex表示秒
The above is the detailed content of How many types of locks does redis have?. For more information, please follow other related articles on the PHP Chinese website!