option('keys'); $cleanLogs = $this->option('logs'); $retentionDays = (int)$this->option('days'); $dryRun = $this->option('dry-run'); // 如果没有指定清理类型,默认清理所有 if (!$cleanKeys && !$cleanLogs) { $cleanKeys = true; $cleanLogs = true; } $this->info('开始清理过期数据...'); $this->line("保留天数: {$retentionDays}"); $this->line("模式: " . ($dryRun ? '预览模式(不实际删除)' : '实际删除')); $this->line(''); $totalCleaned = 0; // 清理过期的API密钥 if ($cleanKeys) { $totalCleaned += $this->cleanExpiredKeys($dryRun); } // 清理过期的调用日志 if ($cleanLogs) { $totalCleaned += $this->cleanOldLogs($retentionDays, $dryRun); } $this->line(''); $this->info("清理完成!总共处理了 {$totalCleaned} 条记录。"); return 0; } /** * 清理过期的API密钥 * * @param bool $dryRun * @return int */ protected function cleanExpiredKeys(bool $dryRun): int { $this->line('正在检查过期的API密钥...'); // 查找过期的密钥 $expiredKeys = OpenApiKey::where('expires_at', '<', now()) ->where('status', '!=', 'EXPIRED') ->get(); $count = $expiredKeys->count(); if ($count === 0) { $this->line('没有找到过期的API密钥。'); return 0; } $this->line("找到 {$count} 个过期的API密钥:"); foreach ($expiredKeys as $key) { $this->line(" - {$key->key_id} ({$key->name}) - 过期时间: {$key->expires_at}"); } if (!$dryRun) { // 更新状态为过期,而不是删除 $updated = OpenApiKey::where('expires_at', '<', now()) ->where('status', '!=', 'EXPIRED') ->update(['status' => 'EXPIRED']); $this->info("已将 {$updated} 个过期密钥标记为过期状态。"); } return $count; } /** * 清理过期的调用日志 * * @param int $retentionDays * @param bool $dryRun * @return int */ protected function cleanOldLogs(int $retentionDays, bool $dryRun): int { $this->line("正在检查 {$retentionDays} 天前的调用日志..."); $cutoffDate = now()->subDays($retentionDays); // 统计要删除的日志数量 $count = OpenApiLog::where('created_at', '<', $cutoffDate)->count(); if ($count === 0) { $this->line('没有找到需要清理的调用日志。'); return 0; } $this->line("找到 {$count} 条需要清理的调用日志({$cutoffDate} 之前)"); if (!$dryRun) { // 分批删除,避免一次性删除太多数据 $batchSize = 1000; $totalDeleted = 0; do { $deleted = OpenApiLog::where('created_at', '<', $cutoffDate) ->limit($batchSize) ->delete(); $totalDeleted += $deleted; if ($deleted > 0) { $this->line("已删除 {$deleted} 条日志记录..."); } } while ($deleted > 0); $this->info("总共删除了 {$totalDeleted} 条调用日志。"); } return $count; } }