2026-03-03 14:57:28 +08:00
|
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 文件功能:清理房间在线名单的 Redis 缓存
|
|
|
|
|
|
* 用于清除历史遗留的「幽灵在线」脏数据
|
|
|
|
|
|
*
|
|
|
|
|
|
* 执行方式:php artisan room:clear-online-cache
|
|
|
|
|
|
*
|
|
|
|
|
|
* @author ChatRoom Laravel
|
|
|
|
|
|
*
|
|
|
|
|
|
* @version 1.0.0
|
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
|
|
|
|
|
|
|
|
use Illuminate\Console\Command;
|
|
|
|
|
|
use Illuminate\Support\Facades\Redis;
|
|
|
|
|
|
|
|
|
|
|
|
class ClearRoomOnlineCache extends Command
|
|
|
|
|
|
{
|
|
|
|
|
|
/**
|
|
|
|
|
|
* Artisan 命令名称
|
|
|
|
|
|
*
|
|
|
|
|
|
* @var string
|
|
|
|
|
|
*/
|
|
|
|
|
|
protected $signature = 'room:clear-online-cache';
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 命令描述
|
|
|
|
|
|
*
|
|
|
|
|
|
* @var string
|
|
|
|
|
|
*/
|
|
|
|
|
|
protected $description = '清空所有房间的 Redis 在线名单(清除幽灵在线脏数据)';
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 执行命令
|
|
|
|
|
|
*
|
|
|
|
|
|
* 扫描所有 room:*:users Redis Key 并删除,让用户重新进房时写入干净数据。
|
|
|
|
|
|
*/
|
|
|
|
|
|
public function handle(): int
|
|
|
|
|
|
{
|
2026-03-12 15:26:54 +08:00
|
|
|
|
$prefix = config('database.redis.options.prefix', '');
|
|
|
|
|
|
$cursor = '0';
|
2026-03-03 14:57:28 +08:00
|
|
|
|
$cleaned = 0;
|
|
|
|
|
|
|
|
|
|
|
|
$this->info("Redis 前缀:\"{$prefix}\"");
|
|
|
|
|
|
$this->info('开始扫描 room:*:users ...');
|
|
|
|
|
|
|
|
|
|
|
|
do {
|
|
|
|
|
|
[$cursor, $keys] = Redis::scan($cursor, ['match' => $prefix.'room:*:users', 'count' => 100]);
|
|
|
|
|
|
foreach ($keys ?? [] as $fullKey) {
|
|
|
|
|
|
// 去掉 Redis 前缀,还原为 Laravel Facade 使用的短 Key
|
|
|
|
|
|
$shortKey = $prefix ? substr($fullKey, strlen($prefix)) : $fullKey;
|
|
|
|
|
|
Redis::del($shortKey);
|
|
|
|
|
|
$this->line(" ✓ 已清除:{$shortKey}");
|
|
|
|
|
|
$cleaned++;
|
|
|
|
|
|
}
|
|
|
|
|
|
} while ($cursor !== '0');
|
|
|
|
|
|
|
|
|
|
|
|
$this->info("完成!共清理 {$cleaned} 个房间的在线名单。");
|
|
|
|
|
|
$this->info('用户下次进房会重新写入正确数据,人数从 0 开始准确累计。');
|
|
|
|
|
|
|
|
|
|
|
|
return self::SUCCESS;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|