Redis prevents large concurrency under two writes

Source: Internet
Author: User
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} 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.