<?php
class RedisLock{
protected $redis;
protected $config = [
'host'=>'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;
}
?>
Redis锁防止并发
最新推荐文章于 2024-08-12 11:28:02 发布
本文介绍了一个基于PHP的RedisLock类,用于实现并发控制的锁机制。该类通过Redis的setnx命令进行加锁,并检查锁的有效性,确保在超时后能够正确释放锁。示例代码展示了如何创建、使用和解锁Redis锁。
摘要由CSDN通过智能技术生成