修復 too many connection 問題

This commit is contained in:
2025-09-21 02:46:16 +08:00
parent a36ab3c98d
commit 808d5bb52c
36 changed files with 5582 additions and 249 deletions

View File

@@ -0,0 +1,122 @@
// =====================================================
// 連線監控 API
// =====================================================
import { NextRequest, NextResponse } from 'next/server';
import { smartPool } from '@/lib/smart-connection-pool';
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const action = searchParams.get('action') || 'stats';
switch (action) {
case 'stats':
// 獲取連線統計
const stats = smartPool.getConnectionStats();
return NextResponse.json({
success: true,
message: '連線統計獲取成功',
data: stats
});
case 'cleanup':
// 強制清理連線
console.log('🧹 執行強制連線清理...');
smartPool.forceCleanup();
const newStats = smartPool.getConnectionStats();
return NextResponse.json({
success: true,
message: '連線清理完成',
data: newStats
});
case 'test':
// 測試智能連線
try {
const testResult = await smartPool.executeQueryOne(
'SELECT 1 as test_value',
[],
{ userId: 'test', sessionId: 'test-session', requestId: 'test-request' }
);
return NextResponse.json({
success: true,
message: '智能連線測試成功',
data: {
testResult,
stats: smartPool.getConnectionStats()
}
});
} catch (error) {
return NextResponse.json({
success: false,
error: '智能連線測試失敗',
details: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
default:
return NextResponse.json({
success: false,
error: '無效的操作參數',
availableActions: ['stats', 'cleanup', 'test']
}, { status: 400 });
}
} catch (error) {
console.error('❌ 連線監控 API 錯誤:', error);
return NextResponse.json({
success: false,
error: 'API 請求失敗',
details: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
}
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { action, maxIdleTime, maxConnectionAge } = body;
switch (action) {
case 'config':
// 更新清理配置
smartPool.setCleanupParams(maxIdleTime, maxConnectionAge);
return NextResponse.json({
success: true,
message: '清理配置更新成功',
data: {
maxIdleTime: maxIdleTime || '未變更',
maxConnectionAge: maxConnectionAge || '未變更'
}
});
case 'cleanup':
// 強制清理連線
console.log('🧹 執行強制連線清理...');
smartPool.forceCleanup();
const stats = smartPool.getConnectionStats();
return NextResponse.json({
success: true,
message: '連線清理完成',
data: stats
});
default:
return NextResponse.json({
success: false,
error: '無效的操作參數',
availableActions: ['config', 'cleanup']
}, { status: 400 });
}
} catch (error) {
console.error('❌ 連線監控 POST API 錯誤:', error);
return NextResponse.json({
success: false,
error: 'API 請求失敗',
details: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
}