66 lines
1.8 KiB
PHP
66 lines
1.8 KiB
PHP
|
|
<?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
|
|||
|
|
{
|
|||
|
|
$prefix = config('database.redis.options.prefix', '');
|
|||
|
|
$cursor = '0';
|
|||
|
|
$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;
|
|||
|
|
}
|
|||
|
|
}
|