# PHP基于Redis简单的分布式锁实现

**URL:** <https://www.shiqidu.com/t/topic/1757>\
**Category:** 开发调优\
**Tags:** PHP, Redis\
**Created:** [2026 年8 月 11 日 12:51 UTC](https://www.shiqidu.com/t/topic/1757 "2026-08-11T12:51:01Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

作者： ![yeqiu](https://www.shiqidu.com/user_avatar/www.shiqidu.com/yeqiu/32/14_2.png) [@yeqiu](https://www.shiqidu.com/u/yeqiu)\
发布日期： [2026 年8 月 11 日 12:51 UTC](https://www.shiqidu.com/t/topic/1757/1 "2026-08-11T12:51:01Z")

</div>

不考虑锁自动续期情况下的最小实现

```php
/**
 * 加锁
 *
 * @param string $lockKey
 * @param int $ex
 * @return string|false
 */
private function lock($lockKey, $ex = 120)
{
    $token = uniqid('', true);

    $result = Redis::rawCommand(
        'set',
        $lockKey,
        $token,
        'EX',
        $ex,
        'NX'
    );

    return $result ? $token : false;
}

/**
 * 解锁
 *
 * @param string $lockKey
 * @param string $token
 * @return bool
 */
private function unlock($lockKey, $token)
{
    $lua = "
        if redis.call('get', KEYS[1]) == ARGV[1] then
            return redis.call('del', KEYS[1])
        else
            return 0
        end
    ";

    return (bool) Redis::eval($lua, 1, $lockKey, $token);
}

```
