修正資料庫未關閉問題
This commit is contained in:
66
app/api/admin/force-cleanup/route.ts
Normal file
66
app/api/admin/force-cleanup/route.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
// =====================================================
|
||||
// 強制清理連線 API
|
||||
// =====================================================
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/database';
|
||||
import { connectionMonitor } from '@/lib/connection-monitor';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
console.log('🧹 開始強制清理資料庫連線...');
|
||||
|
||||
// 獲取清理前的連線狀態
|
||||
const beforeStats = await connectionMonitor.getConnectionStats();
|
||||
console.log(`清理前連線數: ${beforeStats.activeConnections}`);
|
||||
|
||||
// 強制關閉連線池
|
||||
try {
|
||||
await db.close();
|
||||
console.log('✅ 主要資料庫連線池已關閉');
|
||||
} catch (error) {
|
||||
console.error('❌ 關閉主要連線池失敗:', error);
|
||||
}
|
||||
|
||||
// 等待一段時間讓連線完全關閉
|
||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
||||
|
||||
// 重新初始化連線池
|
||||
try {
|
||||
// 重新創建連線池實例
|
||||
const { Database } = await import('@/lib/database');
|
||||
const newDb = Database.getInstance();
|
||||
console.log('✅ 資料庫連線池已重新初始化');
|
||||
} catch (error) {
|
||||
console.error('❌ 重新初始化連線池失敗:', error);
|
||||
}
|
||||
|
||||
// 獲取清理後的連線狀態
|
||||
const afterStats = await connectionMonitor.getConnectionStats();
|
||||
console.log(`清理後連線數: ${afterStats.activeConnections}`);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '強制清理完成',
|
||||
data: {
|
||||
before: {
|
||||
activeConnections: beforeStats.activeConnections,
|
||||
usagePercentage: beforeStats.usagePercentage
|
||||
},
|
||||
after: {
|
||||
activeConnections: afterStats.activeConnections,
|
||||
usagePercentage: afterStats.usagePercentage
|
||||
},
|
||||
cleaned: beforeStats.activeConnections - afterStats.activeConnections
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('強制清理失敗:', error);
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
message: '強制清理失敗',
|
||||
error: error instanceof Error ? error.message : '未知錯誤'
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user