Redisロック同時発生防止
1813 ワード
'127.0.0.1',
'port'=>'6379',
'timeout'=>'0',
'auth'=>'',
'reserved'=>null,
'retry_interval'=>100,
];
public function __construct($config = []){
$this->config = !empty($config)?array_merge($this->config,$config):$this->config;
$this->redis = $this->connect($this->config);
}
public function lock($name,$expire=5){
$is_lock = $this->redis->setnx($name,time()+$expire);// , , 1, 0
if(!empty($is_lock)){
$lock_time = $this->redis->get($name);
if(time()>$lock_time){
$this->unlock($name);
$is_lock = $this->redis->setnx($name,time()+$expire);
}
}
return $is_lock?true:false;
}
public function unlock($name){
return $this->redis->del($name);
}
private function connect($config){
try{
$redis = new Redis();
$redis->connect($config['host'],$config['port'],$config['timeout'],$config['reserved'],$config['retry_interval']);
if(!empty($config['auth'])){
$redis->auth($config['auth']);
}
}catch(RedisException $e){
throw new Exception($e->getMessage());
return false;
}
return $redis;
}
}
$redisLock = new RedisLock();
$lock = $redisLock->lock("test",10);
if($lock){
echo 1111;
$redisLock->unlock("test");
}else{
echo 222;
}
?>