原文作者: 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