使用 Laravel\Framework\Redis\Lock 或类似封装时,看门狗通过后台协程/线程定期执行 EVAL 脚本检查锁是否仍归当前进程所有,若是则续期。核心是原子性判断与更新,避免死锁。

看门狗的 EVAL 原子逻辑
分布式锁的续期必须保证“检查-续期”一步完成,否则中间状态会导致其他客户端抢占。Redis 的 Lua 脚本天然支持原子操作,适合此场景。

脚本先获取锁对应的 value(通常包含进程ID或唯一标识),验证其是否与当前请求一致。若一致,则重置过期时间;若不一致,说明锁已释放或被他人持有,脚本返回失败。这种机制确保了即使在高并发下,也只有合法的锁持有者能续期。
PHP 中的 Timer 实现细节
在 PHP-FPM 模式下,由于没有常驻内存的协程,看门狗通常依赖外部定时器或异步扩展(如 Swoole、Workerman)来实现周期性任务。这里以 Swoole 协程为例展示完整实现。

<?php
namespace App\Services;
use Illuminate\Support\Facades\Redis;
use Swoole\Coroutine;
class DistributedLock
{
private string $key;
private string $value;
private int $ttl;
private ?Coroutine $timer = null;
private bool $isLocked = false;
public function __construct(string $key, int $ttl = 10)
{
$this->key = $key;
$this->ttl = $ttl;
$this->value = uniqid();
}
public function acquire(): bool
{
if ($this->isLocked) return true;
// 使用 SETNX 获取锁,设置过期时间防止死锁
$result = Redis::rawCommand('SET', $this->key, $this->value, 'EX', $this->ttl, 'NX');
if ($result) {
$this->isLocked = true;
$this->startWatchdog();
return true;
}
return false;
}
private function startWatchdog(): void
{
// 每 ttl/3 秒续期一次
$interval = $this->ttl / 3;
$this->timer = Coroutine::create(function () use ($interval) {
while ($this->isLocked && $this->timer) {
sleep($interval);
if (!$this->renew()) {
break;
}
}
});
}
private function renew(): bool
{
// Lua 脚本:仅当 value 匹配时才延长过期时间
$lua = '
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("EXPIRE", KEYS[1], ARGV[2])
else
return 0
end
';
$result = Redis::eval($lua, 1, $this->key, $this->value, $this->ttl);
return (bool)$result;
}
public function release(): void
{
if (!$this->isLocked) return;
// 取消定时器
if ($this->timer) {
$this->timer = null;
}
// 原子删除锁
$lua = '
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
else
return 0
end
';
Redis::eval($lua, 1, $this->key, $this->value);
$this->isLocked = false;
}
}
// 使用示例
Coroutine::run(function () {
$lock = new DistributedLock('my_lock_key', 10);
try {
if ($lock->acquire()) {
echo "Lock acquired.\n";
// 模拟业务处理
sleep(5);
echo "Processing done.\n";
} else {
echo "Failed to acquire lock.\n";
}
} finally {
$lock->release();
echo "Lock released.\n";
}
});
运行上述 Swoole 协程代码,输出将显示 “Lock acquired.”、“Processing done.” 和 “Lock released.”。若在 sleep(5) 期间重启服务,看门狗会自动停止,不会尝试续期已不存在的锁实例。若手动修改 Redis 中该 key 的值,renew() 将返回 false,看门狗循环终止,确保安全性。
代码定义了一个 DistributedLock 类,内部维护一个协程定时器。每次成功获取锁后,启动定时器循环调用续期方法。注意处理异常退出时的资源清理,防止定时器泄漏。
异常中断时的 finally 清理
当业务逻辑抛出异常或正常结束,必须显式释放锁并停止看门狗定时器。否则定时器可能继续尝试续期一个已失效的锁,造成无效网络开销甚至误删他人锁。
在 try...catch...finally 结构中,finally 块负责调用 release() 方法。该方法不仅删除 Redis 键,还要取消之前注册的协程定时器。确保在进程退出前所有后台任务都已终止,避免僵尸进程残留。