Home > Database > Redis > body text

What are the common ways to lock redis?

王林
Release: 2020-12-30 17:10:52
forward
2962 people have browsed it

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;));
Copy after login

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;));
Copy after login

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;));
Copy after login

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;]);
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template