redis加锁的常用方式有哪几种

redis加锁的常用方式有哪几种

常用的加锁方式有:

(学习视频分享:redis视频教程)

一、incr加锁

<?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;));

二、setnx加锁

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

三、set加锁

<?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;));

四、防止死锁

<?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;]);

相关推荐:redis教程

以上就是redis加锁的常用方式有哪几种的详细内容,更多请关注其它相关文章!