PHP calls Redis into read and write operations, large concurrency will appear: Read Key1, no content is written to the content, but the large concurrency will appear at the same time a number of PHP process write, this time need to add a lock, that is to get the lock PHP process has permission to write.
$lock _key = ' Lock_prefix '. $redis _key; $is _lock = $redis->setnx ($lock _key, 1); Locking if ($is _lock = = true) {//Get lock Permissions $redis->setex ($redis _key, $expire, $data);//write content //release lock $ Redis->del ($lock _key); } else{return true;//Get no lock permission, return directly }
The idea is that the key,setnx to set a lock is an atomic operation, only one process can write successfully, and the write successfully returns True (meaning Get lock permission), then writes the content and then releases the lock key. The process that gets the lock cannot be returned directly. However, there is a situation, the process of obtaining lock permissions, to obtain a lock after running an error, resulting in no release lock, then has not been able to write the content, then you need to take the lock permissions of the process to determine the remaining validity of the lock time, if 1 is the effective time to set the lock is 5 seconds (reserved 5 seconds to get the More than enough). The Modified code:
$lock _key = ' lock_prefix '. $redis _key; $is _lock = $redis->setnx ($lock _key, 1); Locking if ($is _lock = = true) {//Get Lock Permissions $redis->setex ($redis _key, $expire, $data);//write content//release lock $redis-& Gt;del ($lock _key); }else{//Prevent deadlock if ($redis->ttl ($lock _key) = =-1) {$redis->expire ($lock _key, 5); } return true; Get no lock permission, return directly}