<?php

namespace App\Utils;


use EasySwoole\Component\Singleton;
use EasySwoole\Redis\Redis as ESRedis;
use EasySwoole\RedisPool\RedisPool;
use EasySwoole\Utility\Random;

class RedisLock
{
    use Singleton;

    const  KEY_PREFIX = 'lock:key:';
    const  TTL        = 60;


    /**
     * 加锁
     * User:gan
     * Date:2021/10/12
     * Time:9:44 上午
     * @param string $key 加锁key
     * @param int $ttl 默认时间,单位秒
     * @return mixed|null
     */
    public function lock(string $key, int $ttl = self::TTL)
    {
        return RedisPool::invoke(function (ESRedis $redis) use ($key, $ttl) {
            $randNum = Random::character(10);
            $result  = $redis->set(self::KEY_PREFIX . $key, $randNum, ['NX', 'PX' => $ttl * 1000]);
            if ($result) {
                return $randNum;
            }
            return null;
        });
    }


    /**
     * 解锁
     * User:gan
     * Date:2021/10/12
     * Time:9:46 上午
     * @param string $key 加锁的key
     * @param string $randNum 加锁内容
     * @return mixed|null
     */
    public function unlock(string $key, string $randNum)
    {
        return RedisPool::invoke(function (ESRedis $redis) use ($key, $randNum) {
            $lua = <<<LUA
if redis.call('get',KEYS[1]) == ARGV[1] then 
   return redis.call('del',KEYS[1]) 
else
   return 0 
end
LUA;
            return $redis->rawCommand(['EVAL', $lua, 1, self::KEY_PREFIX . $key, $randNum]);
        });
    }


    /**
     * 加锁callback
     * User:gan
     * Date:2021/10/12
     * Time:9:47 上午
     * @param string $key 加锁key
     * @param callable $callback 回调函数
     * @param int $ttl 默认时间,单位秒
     * @return bool|mixed
     */
    public function lockFunction(string $key, callable $callback, $ttl = self::TTL)
    {
        $random = $this->lock($key, $ttl);
        if ($random === null) {
            return false;
        }
        $result = call_user_func($callback);
        $this->unlock($key, $random);
        return $result;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

注 1、异步数据丢失。 2、脑裂问题。 所以redis官方针对这种情况提出了红锁(Redlock)的概念。https://redis.io/docs/reference/patterns/distributed-locks/ (opens new window)

可以使用三方中间件去实现 如:Zookeeper,etcd等。