Detailed explanation of redis memory lock and PHP preventing concurrent operations

小云云
Release: 2023-03-22 12:54:02
Original
1858 people have browsed it

This article mainly shares with you the detailed explanation of redis memory lock and PHP preventing concurrent operations. I hope it can help you.

1、redis锁代码:

   /**
     * 获取锁
     * @param  String  $key    锁标识
     * @param  Int     $expire 锁过期时间
     * @return Boolean
     */
    public function lock($key, $expire=5){
        $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);
            }
        }
        return $is_lock? true : false;
    }

    /**
     * 释放锁
     * @param  String  $key 锁标识
     * @return Boolean
     */
    public function unlock($key){
        return $this->_redis->del($key);
    }

2、业务代码(php)
 //设置锁,防止多个用户并发操作连麦超出数量限制
        $lockKey = CacheKeyManage::getLianMaiLockKey($partyId); //缓存key
        $redis = new RedisHelperUtil();
        $lock = $redis->lock($lockKey);
        if(!$lock) {
            for($i=0;$i<3;$i++){ //重试3次,如果3次还未获取倒锁提示繁忙
                $lock = $redis->lock($lockKey);
                if($lock){
                    break;
                }
                sleep(1);
            }
            if(!$lock){
                return self::setAndReturn(ErrorCode::ERR_OTHER_ERR,&#39;服务器获取锁获取不到,$lockKey:&#39;.$lockKey);
            }
        }

        doAction..... //获取到了锁,做自己的业务
Copy after login

The above is the detailed content of Detailed explanation of redis memory lock and PHP preventing concurrent operations. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!