Redis锁防止并发

本文介绍了一个基于PHP的RedisLock类,用于实现并发控制的锁机制。该类通过Redis的setnx命令进行加锁,并检查锁的有效性,确保在超时后能够正确释放锁。示例代码展示了如何创建、使用和解锁Redis锁。
摘要由CSDN通过智能技术生成
<?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;
}
?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值