修復 too many connection 問題
This commit is contained in:
89
lib/database-service-smart.ts
Normal file
89
lib/database-service-smart.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
// =====================================================
|
||||
// 智能資料庫服務範例
|
||||
// =====================================================
|
||||
|
||||
import { smartPool } from './smart-connection-pool';
|
||||
|
||||
// 這是一個範例,展示如何使用智能連線池
|
||||
// 你可以將現有的資料庫服務改為使用這個方式
|
||||
|
||||
export class SmartDatabaseService {
|
||||
// 智能查詢範例
|
||||
static async getUserById(userId: string, requestId?: string) {
|
||||
return await smartPool.executeQueryOne(
|
||||
'SELECT * FROM users WHERE id = ?',
|
||||
[userId],
|
||||
{
|
||||
userId,
|
||||
sessionId: requestId,
|
||||
requestId: `getUserById_${Date.now()}`
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// 智能插入範例
|
||||
static async createUser(userData: any, requestId?: string) {
|
||||
return await smartPool.executeInsert(
|
||||
'INSERT INTO users (name, email, department) VALUES (?, ?, ?)',
|
||||
[userData.name, userData.email, userData.department],
|
||||
{
|
||||
userId: userData.id,
|
||||
sessionId: requestId,
|
||||
requestId: `createUser_${Date.now()}`
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// 智能更新範例
|
||||
static async updateUser(userId: string, userData: any, requestId?: string) {
|
||||
return await smartPool.executeUpdate(
|
||||
'UPDATE users SET name = ?, email = ?, department = ? WHERE id = ?',
|
||||
[userData.name, userData.email, userData.department, userId],
|
||||
{
|
||||
userId,
|
||||
sessionId: requestId,
|
||||
requestId: `updateUser_${Date.now()}`
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// 智能刪除範例
|
||||
static async deleteUser(userId: string, requestId?: string) {
|
||||
return await smartPool.executeDelete(
|
||||
'DELETE FROM users WHERE id = ?',
|
||||
[userId],
|
||||
{
|
||||
userId,
|
||||
sessionId: requestId,
|
||||
requestId: `deleteUser_${Date.now()}`
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// 獲取連線統計
|
||||
static getConnectionStats() {
|
||||
return smartPool.getConnectionStats();
|
||||
}
|
||||
|
||||
// 強制清理連線
|
||||
static forceCleanup() {
|
||||
return smartPool.forceCleanup();
|
||||
}
|
||||
}
|
||||
|
||||
// 使用範例:
|
||||
/*
|
||||
// 在 API 路由中使用
|
||||
export async function GET(request: NextRequest) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const userId = searchParams.get('userId');
|
||||
const requestId = request.headers.get('x-request-id') || 'unknown';
|
||||
|
||||
try {
|
||||
const user = await SmartDatabaseService.getUserById(userId, requestId);
|
||||
return NextResponse.json({ success: true, data: user });
|
||||
} catch (error) {
|
||||
return NextResponse.json({ success: false, error: error.message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
*/
|
Reference in New Issue
Block a user