Home  >  Article  >  Database  >  What are the common ways to lock redis?

What are the common ways to lock redis?

王林
王林forward
2020-12-30 17:10:522897browse

What are the common ways to lock redis?

Commonly used locking methods are:

(Learning video sharing: redis video tutorial)

1. Add incr Lock

<?php
$redis  =  new Redis();
$redis->connect(&#39;127.0.0.1&#39;);
$redis->multi();
$redis->incr(&#39;number&#39;);
//$redis->decr(&#39;number&#39;);
//$redis->expire(&#39;number&#39;, -1);
var_dump($redis->get(&#39;number&#39;));
var_dump($redis->ttl(&#39;number&#39;));

2. Setnx lock

<?php
$redis->setnx(&#39;name&#39;, &#39;felix&#39;);
var_dump($redis->get(&#39;name&#39;));
var_dump($redis->ttl(&#39;name&#39;));

3. Set lock

<?php
$redis->set(&#39;like&#39;, &#39;chuangxi&#39;, [&#39;nx&#39;, &#39;ex&#39; => 10]);
//$redis->del(&#39;like&#39;);
var_dump($redis->get(&#39;like&#39;));
var_dump($redis->ttl(&#39;like&#39;));

4. Prevent deadlock

<?php
$isLock = false;
do {
    $isLock = $redis->set(&#39;like&#39;, &#39;a&#39;, [&#39;nx&#39;, &#39;ex&#39; => 10]);
    if($isLock) {
        if($redis->get(&#39;like&#39;) == &#39;a&#39;) {
            //执行逻辑
            $redis->del(&#39;like&#39;);
            continue;
        }
    } else {
        usleep(5000);
    }
} while (!$isLock);
 
//redis事务
$redis->set();
$redis->watch([&#39;number&#39;, &#39;like&#39;]);

Related recommendations: redis tutorial

The above is the detailed content of What are the common ways to lock redis?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete