yii2簡(jiǎn)單實(shí)現(xiàn)redis消息隊(duì)列

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

生產(chǎn)者代碼示例
public function producer(){
  $data=[]; //組裝要推送隊(duì)列的業(yè)務(wù)邏輯數(shù)據(jù)
  $key='redisKey';
  $redis=Yii::$app->redis;  
  $redis->lpush($key,json_encode($data));  
  $redis->expire($key, 60*60*24); 
} 
消費(fèi)者代碼示例
public function consumer(){
        $redis=Yii::$app->redis;
        //限制本次隊(duì)列只有一個(gè)進(jìn)程在操作
        self::lockLimit(self::FUEL_LIST_RECORD_LOCK_KEY,2,60*30);
        //獲取當(dāng)前隊(duì)列長(zhǎng)度
        $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)){
                //處理業(yè)務(wù)邏輯
                $record_decode=json_decode($record,true);
            }

        }catch(\Throwable $e){
            //判斷重試次數(shù),這里設(shè)置超過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);
            }
            //打個(gè)日志記錄
            CoreHelper::write(json_encode(['handleRecordLogNew',$e->getMessage()], JSON_UNESCAPED_UNICODE));
        }
    }
    Yii::$app->redis->del(self::FUEL_LIST_RECORD_LOCK_KEY); //業(yè)務(wù)邏輯處理完畢,解鎖

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

消費(fèi)者取數(shù)據(jù)處理有另一種省性能的方案即Lrange+Lrem,這個(gè)具體還沒實(shí)踐過,邏輯上能減少redis連接次數(shù),從而提高程序執(zhí)行效率,等有空實(shí)踐再補(bǔ)上。

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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容