PHP redis 分布式 可重入 锁 LUA脚本
2023-2-27 22:6:54 Author: www.yanglong.pro(查看原文) 阅读量:10 收藏

<?php

namespace App\Ok;

class Locker
{

    public static function lock(string $key, $val, int $ex)
    {
        $val = (string)$val;
        if ($key === '' || $val === '' || $ex <= 0) return false;
        return \Illuminate\Support\Facades\Redis::eval(<<<'LUA'
if redis.call('exists', KEYS[1]) > 0 then
    if redis.call('get', KEYS[1]) == ARGV[1] then
        return redis.call('expire', KEYS[1], ARGV[2])
    else
        return false
    end
else
    return redis.call('set', KEYS[1], ARGV[1], 'NX', 'EX', ARGV[2])
end
LUA, 1, $key, $val, $ex);
    }

    public static function unlock(string $key, $val)
    {
        $val = (string)$val;
        if ($key === '' || $val === '') return false;
        return \Illuminate\Support\Facades\Redis::eval(<<<'LUA'
if redis.call('get', KEYS[1]) == ARGV[1] then
    return redis.call('del', KEYS[1])
else
    return 0
end
LUA, 1, $key, $val);
    }
}

文章来源: https://www.yanglong.pro/php-redis-%e5%88%86%e5%b8%83%e5%bc%8f-%e5%8f%af%e9%87%8d%e5%85%a5-%e9%94%81/
如有侵权请联系:admin#unsafe.sh