<?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 业务锁
本文网址:.
本文标签:redis 锁
站长声明:本站部分信息来自网络,如有侵权请联系站长删除!