108 lines
3.5 KiB
PHP
108 lines
3.5 KiB
PHP
<?php
|
||
declare (strict_types = 1);
|
||
|
||
namespace app\command;
|
||
|
||
use app\common\model\Goods as GoodsModel;
|
||
use app\common\model\OrderList;
|
||
use app\common\server\RedisHelper;
|
||
use think\console\Command;
|
||
use think\console\Input;
|
||
use think\console\Output;
|
||
use think\facade\Db;
|
||
|
||
/**
|
||
* 更新盒子热度值到Redis命令 php think UpdateGoodsHeat
|
||
*/
|
||
class UpdateGoodsHeat extends Command
|
||
{
|
||
// 盒子热度值的Redis缓存时间(秒)
|
||
protected $cacheTime = 300; // 5分钟
|
||
|
||
// 统计中奖记录的商品ID范围(和Goods类中的定义保持一致)
|
||
protected $shangCountIdRange = [10, 38];
|
||
|
||
/**
|
||
* 配置命令
|
||
*/
|
||
protected function configure()
|
||
{
|
||
$this->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;
|
||
}
|
||
}
|
||
}
|