PHP uses Redis to realize the method of preventing secondary writing under large concurrency

  • 2021-08-10 07:04:32
  • OfStack

In this paper, an example is given to describe the method of preventing 2 writes under large concurrency by PHP using Redis. Share it for your reference, as follows:

PHP calls redis for read and write operations. Under large concurrency, key1 will be read, and content will be written if there is no content. However, under large concurrency, multiple php processes will be written at the same time. At this time, a lock needs to be added, that is, the php process that acquired the lock has permission to write.


$lock_key = 'LOCK_PREFIX' . $redis_key;
$is_lock = $redis->setnx($lock_key, 1); //  Lock 
if($is_lock == true){ //  Getting Lock Permissions 
  $redis->setex($redis_key, $expire, $data); //  Write content 
  //  Release lock 
  $redis->del($lock_key);
}else{
  return true; //  Unable to get the lock permission, return directly 
}

The idea is: setting key and setnx of one lock is atomic operation, only one process can write successfully, and returning true after writing successfully (indicating obtaining lock permission), then writing the content and releasing the lock, that is, deleting the lock key. Processes that cannot acquire the lock return directly. But there is a situation here, The process that acquires the lock authority reports an error after acquiring the lock, resulting in no release of the lock, so the content cannot be written directly. At this time, the process that cannot get the lock authority needs to judge the remaining effective time of the lock. If it is-1, the effective time of the lock is set to 5 seconds (reserving 5 seconds for the running time of the process that gets the lock is enough). Improved code:


$lock_key = 'LOCK_PREFIX' . $redis_key;
$is_lock = $redis->setnx($lock_key, 1); //  Lock 
if($is_lock == true){ //  Getting Lock Permissions 
  $redis->setex($redis_key, $expire, $data); //  Write content 
  //  Release lock 
  $redis->del($lock_key);
}else{
  //  Deadlock prevention 
  if($redis->ttl($lock_key) == -1){
    $redis->expire($lock_key, 5);
  }
  return true; //  Unable to get the lock permission, return directly 
}

For more readers interested in PHP related content, please check the topics on this site: "Summary of php+redis Database Programming Skills", "Introduction to php Object-Oriented Programming", "Introduction to PHP Basic Syntax", "Encyclopedia of PHP Array (Array) Operation Skills", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation Skills" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: