'use client'; import React, { useState, useEffect } from 'react'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; import { Alert, AlertDescription } from '@/components/ui/alert'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Loader2, Database, Trash2, Settings, Activity, Clock, Users } from 'lucide-react'; interface ConnectionStats { totalConnections: number; idleConnections: number; oldConnections: number; maxIdleTime: number; maxConnectionAge: number; connections: Array<{ createdAt: string; lastUsed: string; idleTime: number; age: number; userId?: string; sessionId?: string; }>; } export default function ConnectionMonitorPage() { const [stats, setStats] = useState(null); const [loading, setLoading] = useState(false); const [message, setMessage] = useState(''); const [error, setError] = useState(''); const [maxIdleTime, setMaxIdleTime] = useState(300000); // 5分鐘 const [maxConnectionAge, setMaxConnectionAge] = useState(1800000); // 30分鐘 // 獲取連線統計 const fetchStats = async () => { try { setLoading(true); const response = await fetch('/api/connection-monitor?action=stats'); const data = await response.json(); if (data.success) { setStats(data.data); setMessage('統計更新成功'); setError(''); } else { setError(data.error || '獲取統計失敗'); } } catch (err) { setError('網路錯誤: ' + (err instanceof Error ? err.message : '未知錯誤')); } finally { setLoading(false); } }; // 強制清理連線 const forceCleanup = async () => { if (!confirm('確定要強制清理所有連線嗎?這可能會影響正在進行的操作!')) { return; } try { setLoading(true); const response = await fetch('/api/connection-monitor?action=cleanup'); const data = await response.json(); if (data.success) { setMessage('連線清理完成'); setError(''); await fetchStats(); // 重新獲取統計 } else { setError(data.error || '清理失敗'); } } catch (err) { setError('清理錯誤: ' + (err instanceof Error ? err.message : '未知錯誤')); } finally { setLoading(false); } }; // 測試智能連線 const testConnection = async () => { try { setLoading(true); const response = await fetch('/api/connection-monitor?action=test'); const data = await response.json(); if (data.success) { setMessage('智能連線測試成功'); setError(''); await fetchStats(); // 重新獲取統計 } else { setError(data.error || '測試失敗'); } } catch (err) { setError('測試錯誤: ' + (err instanceof Error ? err.message : '未知錯誤')); } finally { setLoading(false); } }; // 更新清理配置 const updateConfig = async () => { try { setLoading(true); const response = await fetch('/api/connection-monitor', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ action: 'config', maxIdleTime, maxConnectionAge }), }); const data = await response.json(); if (data.success) { setMessage('清理配置更新成功'); setError(''); await fetchStats(); // 重新獲取統計 } else { setError(data.error || '配置更新失敗'); } } catch (err) { setError('配置更新錯誤: ' + (err instanceof Error ? err.message : '未知錯誤')); } finally { setLoading(false); } }; // 格式化時間 const formatTime = (ms: number) => { const seconds = Math.floor(ms / 1000); const minutes = Math.floor(seconds / 60); const hours = Math.floor(minutes / 60); if (hours > 0) return `${hours}h ${minutes % 60}m`; if (minutes > 0) return `${minutes}m ${seconds % 60}s`; return `${seconds}s`; }; // 組件載入時獲取統計 useEffect(() => { fetchStats(); // 每30秒自動更新統計 const interval = setInterval(fetchStats, 30000); return () => clearInterval(interval); }, []); return (

連線監控管理

監控和管理資料庫連線的生命週期

{/* 統計概覽 */} {stats && (

總連線數

{stats.totalConnections}

空閒連線

{stats.idleConnections}

舊連線

{stats.oldConnections}

健康狀態

{stats.idleConnections + stats.oldConnections === 0 ? '良好' : '需清理'}

)} {/* 操作按鈕 */} 連線管理 管理和清理資料庫連線
{/* 配置設定 */}
setMaxIdleTime(Number(e.target.value))} placeholder="300000 (5分鐘)" />
setMaxConnectionAge(Number(e.target.value))} placeholder="1800000 (30分鐘)" />
{/* 連線詳情 */} {stats && stats.connections.length > 0 && ( 連線詳情 當前活躍的資料庫連線列表
{stats.connections.map((conn, index) => (
#{index + 1}

創建時間: {new Date(conn.createdAt).toLocaleString()}

最後使用: {new Date(conn.lastUsed).toLocaleString()}

stats.maxIdleTime ? "destructive" : "default"}> 空閒: {formatTime(conn.idleTime)} stats.maxConnectionAge ? "destructive" : "default"}> 年齡: {formatTime(conn.age)} {conn.userId && ( 用戶: {conn.userId} )}
))}
)} {/* 訊息顯示 */} {message && ( {message} )} {error && ( {error} )} {/* 說明資訊 */} 智能連線管理說明

自動清理: 系統每30秒自動檢查並清理空閒或過期的連線

智能追蹤: 追蹤每個連線的創建時間、最後使用時間和用戶信息

即時監控: 實時顯示連線狀態,幫助識別連線洩漏問題

自動釋放: 查詢完成後自動釋放連線,避免連線累積

用戶關閉網頁: 空閒連線會在設定的時間後自動清理

); }