下⾯这个例⼦是利⽤⼀个原⼦性命令操作来限制整个流程的控制 tnx. <?php
require "vendor/autoload.php";
$client = new Predis\Client([
'scheme' => 'tcp',
'host' => '127.0.0.1',earth hour
'port' => 6379,
55届格莱美颁奖典礼
]);
class RedisLock
{
public $objRedis = null;
love in decemberpublic $timeout = 3;
/
**
* @desc 设置redis实例
*
* @param obj object | redis实例
*/
public function __construct($obj)
{
$this->objRedis = $obj;
}
/**
* @desc 获取锁键名
*/
public function getLockCacheKey($key)
{
return "lock_{$key}";
北大青鸟java培训
}
teamleader/**
* @desc 获取锁
*
* @param key string | 要上锁的键名
* @param timeout int | 上锁时间
*/
tallest
public function getLock($key, $timeout = NULL)
{
$timeout = $timeout ? $timeout : $this->timeout;
$lockCacheKey = $this->getLockCacheKey($key);
$expireAt = time() + $timeout;
$isGet = (bool)$this->objRedis->tnx($lockCacheKey, $expireAt);
if ($isGet) {
return $expireAt;
}
while (1) {unit
usleep(10);
$time = time();
$oldExpire = $this->objRedis->get($lockCacheKey);
if ($oldExpire >= $time) {
continue;
}
$newExpire = $time + $timeout;
$expireAt = $this->objRedis->gett($lockCacheKey, $newExpire);
if ($oldExpire != $expireAt) {编程java培训班
continue;
}
$isGet = $newExpire;
break;
}
return $isGet;
}
/**
西雅图是什么意思* @desc 释放锁
*项目负责人 翻译
* @param key string | 加锁的字段
* @param newExpire int | 加锁的截⽌时间