/**
* 分布式锁
* @param $key
* @param $fn
* @param int $expires
* @param int $tryTimes
* @param int $code
* @param string $msg
* @return mixed
* @throws ApiException
*/
public function distributeLock($key, $fn, $expires = 5, $tryTimes = 2, $code = 999, $msg = '请求太频繁,稍后再试!')
{
try {
if (!is_callable($fn, true)) {
throw new ApiException('抱歉,第二个入参[$fn]必须为函数!!', -1);
}
$try = 0;
while (true) {
if ($this->redis->set($this->formatKey($key), 1, ['nx', 'ex' => $expires])) {
break;
}
if ($try > $tryTimes) {
throw new \Exception($msg, $code);
}
$try++;
usleep(50000);//休眠50毫秒
}
$result = call_user_func($fn);
$this->del($key);
} catch (\Exception $e) {
if ($e instanceof ApiException) {
$this->del($key);
} else {
DI()->logger->error(__METHOD__, ['key' => $key, 'code' => $e->getCode(), 'msg' => $e->getMessage()]);
}
throw new ApiException($e->getMessage(), $e->getCode());
}
return $result;
}
简单分布式锁实现(拍黄片)
最新推荐文章于 2024-12-11 10:11:51 发布
本文介绍了一种基于Redis的分布式锁实现方式,通过设置键值对实现加锁,并确保线程安全。文中详细展示了如何使用PHP实现分布式锁,包括设置锁的过期时间、尝试获取锁的次数等。
635

被折叠的 条评论
为什么被折叠?



