Redis锁防止并发

来源:互联网 发布:苹果usb共享电脑网络 编辑:程序博客网 时间:2024/04/28 22:42
<?phpclass 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;}?>

0 0
原创粉丝点击