class LockUtil
{
private static $lock_prefix = 'hi_box_lock_';
/**
* @param $key
* @param string $func 操作方法
* @param int $timeout
* @return bool true 未锁 false 已锁
*/
public static function onLock($key, $func='default', $timeout = 5): bool
{
if (empty($key) || $timeout <= 0) {
return true;
}
/**
* @var $redis Redis
*/
$redis = Cache::store('redis')->handler();
$key = self::$lock_prefix.md5($func) . $key;
// $key 如果存在 设置nx后 是不会重新覆盖set
return $redis->set($key, 1, ['nx', 'ex' => $timeout]);
}
public static function unLock($key,$func='defa
ult')
{
/**
* @var $redis Redis
*/
$redis = Cache::store('redis')->handler();
$key = self::$lock_prefix .md5($func). $key;
//监听Redis key防止【解锁事务执行过程中】被修改或删除,提交事务后会自动取消监控
$redis->watch($key);
if ($redis->get($key)) {
$redis->multi()->del($key)->exec();
}
$redis->unwatch();
}
}