setName('update_goods_heat') ->setDescription('更新所有盒子的热度值到Redis中'); } /** * 执行命令 * * @param Input $input * @param Output $output * @return int */ protected function execute(Input $input, Output $output) { $startTime = microtime(true); $output->writeln('开始更新盒子热度值到Redis...'); // 获取Redis实例 $redis = (new RedisHelper())->getRedis(); try { // 获取所有上架的盒子ID $goodsIds = GoodsModel::where('status', 1) ->field('id') ->select() ->column('id'); if (empty($goodsIds)) { $output->writeln('没有找到上架的盒子'); return 0; } $output->writeln('找到 ' . count($goodsIds) . ' 个上架的盒子'); // 更新到Redis $updatedCount = 0; $successCount = 0; $failCount = 0; // 逐个查询盒子的参与次数并更新到Redis foreach ($goodsIds as $goodsId) { try { // 查询单个盒子的参与次数(命中索引) $count = OrderList::where('goods_id', '=', $goodsId) ->where('shang_id', 'between', $this->shangCountIdRange) ->where('parent_goods_list_id', '=', 0) ->count(); // 构建缓存键 $cacheKey = "order_goods_count:{$goodsId}"; // 存入Redis,设置5分钟过期时间 $redis->set($cacheKey, $count, $this->cacheTime); $successCount++; } catch (\Exception $e) { $output->writeln("更新盒子(ID:{$goodsId})热度值失败: {$e->getMessage()}"); $failCount++; } $updatedCount++; // 每处理50个盒子输出一次进度 if ($updatedCount % 50 == 0) { $output->writeln("已处理 {$updatedCount} 个盒子..."); } } $endTime = microtime(true); $executionTime = round($endTime - $startTime, 2); $output->writeln("处理完成! 总计 {$updatedCount} 个盒子,成功 {$successCount} 个,失败 {$failCount} 个"); $output->writeln("执行耗时: {$executionTime} 秒"); return 0; } catch (\Exception $e) { $output->writeln("更新盒子热度值失败: {$e->getMessage()}"); return 1; } } }