Home >Backend Development >PHP Tutorial >Detailed explanation of redis memory lock and PHP preventing concurrent operations
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,'服务器获取锁获取不到,$lockKey:'.$lockKey); } } doAction..... //获取到了锁,做自己的业务
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!