|
<?php
/**
* Created by phpStorm
* Date: 2020/6/10/0010
* Time: 17:38
*/
namespace common\helper;
use Yii;
class LockHelper
{
private static $instance;
private $redis;
private function __construct()
{
if (!$this->redis instanceof Yii::$app->redis) {
$this->redis = Yii::$app->redis;
}
}
public static function instance()
{
if (!self::$instance || !self::$instance instanceof self) {
self::$instance = new static();
}
return self::$instance;
}
public static function getMicroTime()
{
$time = microtime();
list($usec, $sec) = explode(" ", $time);
return round(((float)$usec + (float)$sec) * 1000);
}
public function __call($func, $params)
{
return call_user_func_array([$this->redis, $func], $params);
}
/*
* 获取锁令牌 @todo 是否需要拼接特征码?
*/
public static function getToken($preFix = '')
{
$preFix = mt_rand(1111, 9999);
$preFix = $preFix . self::getMicroTime();
return $preFix;
}
/*
* 加锁
* @params $ttl 过期时间(s)
*/
public function setLock($key, $token, $ttl = 10)
{
if (!$key) return false;
$redis = $this->redis;
$isLock = $redis->set($key, $token, 'NX', 'EX', $ttl);
if ($isLock) {
return true;
}
return false;
}
public function unLock($key, $val)
{
if ($this->redis->get($key) == $val) {
return $this->redis->del($key);
}
return false;
}
final private function __clone()
{
// TODO: Implement __clone() method.
}
}
|