redis 分布式锁

2018-01-21  本文已影响0人  夢醒皆涳

利用setnx命令的原子性

 /**
     * 获取锁
     * @param  String  $key    锁标识
     * @param  Int     $expire 锁过期时间
     * @return Boolean
     */
    public function lock($key, $expire=5){
        //time()+$expire 如果存在返回0 不存在则设置此值并返回1
        $is_lock = $this->_redis->setnx($key, time()+$expire);

        // 锁存在
        if(!$is_lock){

            // 判断锁是否过期
            $lock_time = $this->_redis->get($key);

            // 锁已过期,删除锁,重新获取
            if(time()>$lock_time){
                $this->unlock($key);
                $is_lock = $this->_redis->setnx($key, time()+$expire);
            }
        }
        //设置锁过期时间
        $this->_redis->setTimeout($key, $expire);
        return $is_lock? true : false;
    }
上一篇 下一篇

猜你喜欢

热点阅读