Common ways to lock redis

"The ancients are powerless in learning, but the young and strong kung fu begins with old age."

There are several common ways to lock in redis. Locking in redis is a common operation for comparison. In order to prevent various memory allocation problems caused by concurrency, we should know and understand how to choose how to lock correctly and efficiently. , It’s not easy to make code words, and it’s even harder to produce a good product. If you are not particularly lucky, please work hard first, don’t fail because of laziness, and pretend to attribute the reason to yourself. You must work hard to appear effortless. If this article can bring you a little help, I hope to show your support to Little Brother Flying Rabbit with one click and three links. Thank you all friends.
table of Contents
One, incr lock
Two, setnx lock
Three, set lock
Fourth, prevent deadlock

One, incr lock

  • If the key does not exist, initialize the key to 0, and then increment it by 1
<?php$lock = $redis->get($key); if (!$lock) {  /* ..加锁.. */  $redis->incr($key);   /* ..加锁之后你的逻辑.. */   /* ..删除锁,直接删除或者设置过期时间也行.. */  $redis->del($key);}

Two, setnx lock

  • If the key does not exist, set the key to value
<?php$lock = $redis->get($key);if (!$lock) {   /* ..加锁.. */   $redis->setNX($key, $value);    /* ..加锁之后你的逻辑.. */    /* ..删除锁,直接删除或者设置过期时间也行.. */   $redis->del($key);}

Three, set lock

  • Same as setnx lock
<?php$lock = $redis->get($key);if (!$lock) {   /* ..加锁.. */   $redis->set($key, $value);    /* ..加锁之后你的逻辑.. */    /* ..删除锁,直接删除或者设置过期时间也行.. */   $redis->del($key);}

Fourth, prevent deadlock

  • Loop to prevent lock failure
  • Waiting time in order to reduce the frequency of strong locks
  • Random key is added for accidental deletion
<?php//循环防止加锁失败do {  $timeout = 10;  $key = 'autofelix_lock';  $rand = mt_rand(10000, 99999);  $value = 'autofelix_' . $rand; //随机值,防止误删除  $lock = Redis::set($key, $value, 'ex', $timeout, 'nx'); //ex 秒   if ($lock) {     if (Redis::get($key) == $value) {             /* ..执行自己的逻辑.. */             /* ..删除锁.. */             Redis::del($key);              /* ..跳出循环.. */              continue;         }     } else {          /* ..降低抢锁频率.. */          usleep(5000);      }} while (!$lock);