yii2简单实现redis消息队列

原文作者: xingguang
原文链接:https://www.tiance.club/post/1297686480.html

生产者代码示例
public function producer(){
  $data=[]; //组装要推送队列的业务逻辑数据
  $key='redisKey';
  $redis=Yii::$app->redis;  
  $redis->lpush($key,json_encode($data));  
  $redis->expire($key, 60*60*24); 
} 
消费者代码示例
public function consumer(){
        $redis=Yii::$app->redis;
        //限制本次队列只有一个进程在操作
        self::lockLimit(self::FUEL_LIST_RECORD_LOCK_KEY,2,60*30);
        //获取当前队列长度
        $length = $redis->llen(self::FUEL_LIST_RECORD_LOG_KEY);

    for($i=0;$i<$length;$i++){
        try{
            $record = $redis->rpop(self::FUEL_LIST_RECORD_LOG_KEY);
            if(!empty($record)){
                //处理业务逻辑
                $record_decode=json_decode($record,true);
            }

        }catch(Throwable $e){
            //判断重试次数,这里设置超过3次重试就不再重试
            if(!isset($record_decode['try_count']))$record_decode['try_count']=0;
            if(isset($record_decode['try_count']) && $record_decode['try_count']<3 ){
                ++$record_decode['try_count'];
                $redis->lpush(self::FUEL_LIST_RECORD_LOG_KEY,json_encode($record_decode));
                $redis->expire(self::FUEL_LIST_RECORD_LOG_KEY, 60*60*24);
            }
            //打个日志记录
            CoreHelper::write(json_encode(['handleRecordLogNew',$e->getMessage()], JSON_UNESCAPED_UNICODE));
        }
    }
    Yii::$app->redis->del(self::FUEL_LIST_RECORD_LOCK_KEY); //业务逻辑处理完毕,解锁

}
原文作者: xingguang
原文链接:[https://www.tiance.club/post/1297686480.html](https://www.tiance.club/post/1297686480.html)

消费者取数据处理有另一种省性能的方案即Lrange+Lrem,这个具体还没实践过,逻辑上能减少redis连接次数,从而提高程序执行效率,等有空实践再补上。

原文作者: xingguang
原文链接:https://www.tiance.club/post/1297686480.html

原文地址:https://www.cnblogs.com/yizhidaozuihou/p/12829920.html