Files
tougao/application/api/job/ReviewerScore.php
2025-07-07 17:54:17 +08:00

103 lines
3.7 KiB
PHP

<?php
namespace app\api\job;
use think\queue\Job;
use app\common\QueueJob;
use app\common\Reviewer;
class ReviewerScore
{
// 最多重试1次
public $tries = 1;
// 任务日志添加
public function addLog($aParam = [])
{
//实例化
$oQueueJob = new QueueJob;
$iLogId = $oQueueJob->addLog($aParam);
return $iLogId;
}
// 任务日志修改
public function updateLog($aParam = [])
{
//实例化
$oQueueJob = new QueueJob;
return $oQueueJob->updateLog($aParam);
}
// 审稿人评分
public function fire(Job $job, $data)
{
$sLogPath = ROOT_PATH.'public/queue_log/ReviewerScore_'.date('Ymd').'.log';
$sTime = date('H:i:s');
file_put_contents($sLogPath,'-----------Queue job started:'.$sTime.'-----------');
//参数
$iArticleId = empty($data['article_id']) ? 0 : $data['article_id'];//文章ID
$iReviewerId = empty($data['reviewer_id']) ? 0 : $data['reviewer_id'];//审稿人ID
$iArtRevId = empty($data['art_rev_id']) ? 0 : $data['art_rev_id'];//主键ID
//获取方法名
$sClassName = get_class($this);
// 检查任务是否已处理(基于业务唯一标识)
$sRedisKey = $sClassName.'/'.$iArticleId.'/'.$iReviewerId.'/'.$iArtRevId;
$sRedisKey = md5($sRedisKey);
//判断Redis是否存在
$oQueueJob = new QueueJob;
$result = $oQueueJob->setRedisLabel(['redis_key' => $sRedisKey]);
if($result != 1){
$job->delete();
file_put_contents($sLogPath,'-----------Queue job already:'.$result."===".$sRedisKey.'==='.$iArticleId."===".$sTime.'-----------');
return;
}
//任务数组
$aParam = [
'job_id' => $sRedisKey,
'job_class' => $sClassName,
'status' => 0,
'create_time' => time(),
'params' => json_encode($data, JSON_UNESCAPED_UNICODE)
];
//执行任务
try {
//添加任务日志
$sMsg = '审稿人评分任务处理成功';
$iLogId = $this->addLog($aParam);
$aParam = ['article_id' => $iArticleId,'reviewer_id' => $iReviewerId,'art_rev_id' => $iArtRevId];
$oReviewer = new Reviewer;
$aResult = json_decode($oReviewer->score($aParam),true);
$sMsg = empty($aResult['msg']) ? '给审稿人评分处理失败' : $aResult['msg'];
//更新任务状态
$aParam = ['log_id' => $iLogId,'status' => 1,'update_time' => time(),'error' => $sMsg];
$oQueueJob->updateLog($aParam);
//删除任务
$job->delete();
file_put_contents($sLogPath,'-----------Queue job end:'.$sTime.'-----------');
} catch (\Exception $e) {
// 2. 记录失败日志
$aParam['status'] = 2; // 标记状态为"失败"
$sMsg = empty($e->getMessage()) ? '任务出错' : $e->getMessage(); // 错误信息
$aParam['error'] = $sMsg;
$this->addLog($aParam); // 调用日志记录方法
if ($job->attempts() > $this->tries) {
//如果任务尝试次数超过最大重试次数
$job->delete(); // 删除任务,不再重试
} else {
// 3. 如果尝试次数未超过最大重试次数,释放任务回队列
$job->release(30); // 30秒后重新尝试执行任务
}
file_put_contents($sLogPath,'-----------Queue job error:'.$sMsg.'-----------'.$sTime);
}finally {
gc_collect_cycles(); // 强制垃圾回收
}
}
}