<?php
namespace lediy\tools;
//redis 锁
use think\facade\Cache;
use think\facade\Log;
class Lock
{
public $redis;
protected $lockIds;
public function __construct()
{
$this->redis = Cache::store('redis')->handler();
}
/**
* @param $name key名称
* @param $expires 过期时间
* @param $num 重试次数
* @param $usleep 重试间隔
* @return bool
*/
public function lock($name = 'default', $expires = 10, $num = 5, $usleep = 100000)
{
$res = false;
while ($num-- > 0) {
//获取锁
$value = md5(uniqid());
$res = $this->redis->set($name, $value, ['nx', 'ex' => $expires]);
if ($res) {
Log::write('获取锁成功,' . $name, 'le');
$this->lockIds[$name] = $value;
$res = true;
break;
}
//重试
usleep($usleep);
}
return $res;
}
public function unlock($name = 'default')
{
if (isset($this->lockIds[$name])) {
$localid = $this->lockIds[$name];
$rid = $this->redis->get($name);
if ($localid == $rid) {
$this->redis->del($name);
Log::write('解除锁成功,' . $name, 'le');
return true;
}
}
return false;
}
function __destruct()
{
//Log::write($this->lockIds,'le');
if(!empty($this->lockIds)){
//Log::write(__FUNCTION__.'销毁lock','le');
foreach($this->lockIds as $k=>$v){
//Log::write($k,'le');
$this->unlock($k);
}
}
//方法体
}
}
TP redis 业务锁
最新推荐文章于 2023-08-29 16:30:47 发布