diff --git a/application/common/QueueRedis.php b/application/common/QueueRedis.php index c28faf7..1aaacbf 100644 --- a/application/common/QueueRedis.php +++ b/application/common/QueueRedis.php @@ -124,23 +124,38 @@ LUA; $redis = $this->connect(); } } - // 任务结束时的批量操作 -public function finishJob($sRedisKey, $status, $expire) -{ - try { - $redis = $this->connect(); - // 使用Lua脚本确保原子性 - $script = <<eval($script, [$sRedisKey, $status, $expire], 1) === 1; - } catch (\Exception $e) { - Log::error("Redis完成任务失败: {$e->getMessage()}"); - return false; - } -} + /** + * 标记任务状态并释放锁(带所有权验证) + * @param string $sRedisKey 任务锁的键名 + * @param string $status 状态(completed/failed) + * @param int $expire 状态的过期时间(秒) + * @param string $sRedisValue 锁的值(用于验证所有权) + * @return bool 是否执行成功 + */ + public function finishJob($sRedisKey, $status, $expire, $sRedisValue){ + try { + $redis = $this->connect(); + // Lua 脚本:先验证锁所有权,再设置状态并删除锁 + $script = <<eval($script, [$sRedisKey, $sRedisValue, $status, $expire], 1); + return $result === 1; + } catch (\Exception $e) { + Log::error("Redis完成任务失败: {$e->getMessage()} | 键: {$sRedisKey}"); + return false; + } + } // 记录处理进度 public function recordProcessingStart($key, $totalQuestions) { @@ -163,6 +178,14 @@ LUA; { try { $redis = $this->connect(); + //判断是否执行 + $sStatus = $redis->hGet($key, 'status'); + if (!empty($sStatus) && $sStatus == 'completed') { + return 2; + } + if (!empty($sStatus) && $sStatus == 'processing') { + return 3; + } $redis->hMSet($key, [ 'status' => 'processing', 'total' => $totalQuestions, @@ -172,9 +195,9 @@ LUA; 'queue_2_completed' => 0 ]); $redis->expire($key, 10800); // 6小时过期 - return true; + return 1; } catch (\Exception $e) { - return false; + return 4; } } // 多问题按条件拆分成两个队列更新日志记录