<?php
class Lock {
const REDIS_LOCK_DEFAULT_EXPIRE_TIME = 86400;
protected $redis;
public function __construct($host, $prot, $auth) {
$this->redis = new \Redis();
$this->redis->connect($host, $prot);
if(!empty($auth)){
$this->redis->auth($auth);
}
}
public function lock($scene,$intExpireTime= self::REDIS_LOCK_DEFAULT_EXPIRE_TIME){
if (empty($scene) || $intExpireTime <= 0) {
return false;
}
$lockId = uniqid();
$result = $this->redis->set($scene, $lockId, ['nx', 'ex'=>$intExpireTime]);
return $result ? $lockId : $result;
}
public function unLock($scene, $lockId){
if (empty($scene) || empty($lockId)) {
return false;
}
$this->redis->watch($scene);
$result = $this->redis->get($scene);
if ($result === $lockId) {
$this->redis->multi()->del($scene)->exec();
return true;
}
$this->redis->unwatch();
return false;
}
}
$lock = new Lock('127.0.0.1', 6379, '123456789');
$re = $lock->lock('test', 9999999);
var_dump($re);
echo '<hr/>';
$re2 = $lock->lock('test', 9999999);
var_dump($re2);
echo '<hr/>';
$re3 = $lock->unLock('test', '624567e95bc8c');
var_dump($re3);