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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM