feat: implement connection pooling in DatabasePlugin for improved database connection management
This commit is contained in:
@ -2,6 +2,8 @@ import { Plugin } from "../plugin.class";
|
|||||||
import * as mysql from "mysql2/promise";
|
import * as mysql from "mysql2/promise";
|
||||||
|
|
||||||
export class DatabasePlugin extends Plugin {
|
export class DatabasePlugin extends Plugin {
|
||||||
|
private static connectionPool: Map<string, any> = new Map();
|
||||||
|
|
||||||
constructor(name: string, private dbConnection: any) {
|
constructor(name: string, private dbConnection: any) {
|
||||||
if (!dbConnection || typeof dbConnection.execute !== "function") {
|
if (!dbConnection || typeof dbConnection.execute !== "function") {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
@ -24,6 +26,14 @@ export class DatabasePlugin extends Plugin {
|
|||||||
connectTimeout: number;
|
connectTimeout: number;
|
||||||
}
|
}
|
||||||
): Promise<DatabasePlugin> {
|
): Promise<DatabasePlugin> {
|
||||||
|
const connectionKey = `${config.host}:${config.port}:${config.user}:${config.database}`;
|
||||||
|
|
||||||
|
if (DatabasePlugin.connectionPool.has(connectionKey)) {
|
||||||
|
const existingConnection =
|
||||||
|
DatabasePlugin.connectionPool.get(connectionKey);
|
||||||
|
return new DatabasePlugin(name, existingConnection);
|
||||||
|
}
|
||||||
|
|
||||||
const dbConnection = await mysql.createConnection({
|
const dbConnection = await mysql.createConnection({
|
||||||
host: config.host,
|
host: config.host,
|
||||||
user: config.user,
|
user: config.user,
|
||||||
@ -37,6 +47,7 @@ export class DatabasePlugin extends Plugin {
|
|||||||
|
|
||||||
// await dbConnection.query("SET SESSION MAX_EXECUTION_TIME=2000;");
|
// await dbConnection.query("SET SESSION MAX_EXECUTION_TIME=2000;");
|
||||||
|
|
||||||
|
DatabasePlugin.connectionPool.set(connectionKey, dbConnection);
|
||||||
return new DatabasePlugin(name, dbConnection);
|
return new DatabasePlugin(name, dbConnection);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user