diff --git a/application/common/QueueJob.php b/application/common/QueueJob.php index 3995e5d..895917c 100644 --- a/application/common/QueueJob.php +++ b/application/common/QueueJob.php @@ -8,6 +8,24 @@ class QueueJob //必填参数 protected $aField = ['job_id','job_class','status','create_time','update_time','error','params']; + //定义redis连接 + private $redis; + public function __construct() + { + + $config = \think\Config::get('queue'); + $this->redis = new \Redis(); + $this->redis->connect($config['host'], $config['port']); + + if (!empty($config['password'])) { + $this->redis->auth($config['password']); + } + + $this->redis->select($config['select']); + // 初始化 Redis 连接 + // $this->redis = Cache::store('redis')->handler(); + } + // 记录任务开始 public function addLog($aParam = []) { @@ -78,5 +96,34 @@ class QueueJob } return Cache::get($sRedisKey); } + + + // 使用SETNX原子操作设置锁 + public function setRedisLock($key, $value, $expire) + { + return $this->redis->set($key, $value, ['nx', 'ex' => $expire]); + } + + // 获取Redis值 + public function getRedisValue($key) + { + return $this->redis->get($key); + } + + // 安全释放锁(仅当值匹配时删除) + public function releaseRedisLock($key, $value) + { + + // 使用Lua脚本确保原子性 + $script = <<redis->eval($script, [$key, $value], 1); + } } ?> \ No newline at end of file