redis计数器,redis并发锁

 
  
/**
 * 红包竞猜次数并且设置过期时间
 * @return string
 */
public function incrPacketNumAction($key)
{
    $redis = $this->getRedis();
    $key="packet_".$key;
    $num=$redis->incr($key);
    $time=strtotime(date("Y-m-d",strtotime("+1 days")))-1-time();//过期时间为第二天的0点
    $redis->expire($key,$time);
    return $num;
}
/**
 * 红包竞猜次并发锁
 * @return string
 */
public function PacketLockAction($key,$expire)
{
    $redis = $this->getRedis();
    $key="open_packet_".$key;
    $is_lock = $redis->setnx($key, time()+$expire);
    // 不能获取锁
    if(!$is_lock){
        // 判断锁是否过期
        $lock_time = $redis->get($key);
        // 锁已过期,删除锁,重新获取
        if(time()>$lock_time){
            $this->PacketUnLockAction($key);
            $is_lock = $redis->setnx($key, time()+$expire);
        }
    }
    return $is_lock? true : false;
}

/**
 * 红包竞猜次并发锁解锁
 * @return string
 */
public function PacketUnLockAction($key)
{
    $redis = $this->getRedis();
    $key="open_packet_".$key;
    return $redis->del($key);
}

你可能感兴趣的:(redis,并发锁,计数器)