TP redis 业务锁

全屏阅读
  • 基本信息
<?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);
}
}
//方法体
 
}
}

顶一下
(0)
100%
订阅 回复
踩一下
(0)
100%
» 固定链接:恒富网 » 《TP redis 业务锁》
» 郑重声明:本文由mpxq168发布,所有内容仅代表个人观点。版权归恒富网和mpxq168共有,欢迎转载, 但未经作者同意必须保留此段声明,并给出文章连接,否则保留追究法律责任的权利! 如果本文侵犯了您的权益,请留言。

目前有 0 条留言 其中:访客:0 条, 博主:0 条

给我留言

您必须 [ 登录 ] 才能发表留言!

  • Connection Information

    To perform the requested action, WordPress needs to access your web server. Please enter your FTP credentials to proceed. If you do not remember your credentials, you should contact your web host.

    Connection Type