This commit is contained in:
艾贤凌
2026-03-16 12:05:55 +08:00
parent af3a7c83e8
commit 6d4a72161f
33 changed files with 5671 additions and 178 deletions

View File

@@ -0,0 +1,46 @@
/**
* 游戏区服动态数据库连接工具
*
* 游戏每个区服对应独立的数据库 mir_actor_s{serverId}
* 该模块根据 serverId 动态创建连接池(带缓存,同一区服复用连接)
*
* 使用示例:
* import getGameDB from '../mysql/gameDB.js'
* const db = getGameDB(1)
* const [rows] = await db.query('SELECT ...')
*/
import mysql from 'mysql2'
import config from '../config/index.js'
import * as log4js from '../log4js.js'
// 连接池缓存,避免对同一区服重复创建
const poolCache = new Map()
/**
* 获取指定区服的 MySQL 连接池Promise 包装)
* @param {number} serverId 区服 ID
* @returns {import('mysql2/promise').Pool}
*/
export default function getGameDB(serverId) {
const dbName = `mir_actor_s${serverId}`
if (poolCache.has(dbName)) return poolCache.get(dbName)
const pool = mysql.createPool({
host: config.game.dbHost || config.mysql.host,
port: config.game.dbPort || config.mysql.port,
user: config.game.dbUser || config.mysql.user,
password: config.game.dbPassword || config.mysql.password,
database: dbName,
connectionLimit: 5,
waitForConnections: true,
})
pool.on('error', (err) => {
log4js.mysql.error(`[${dbName}] 连接池错误:`, err.message)
})
const promisePool = pool.promise()
poolCache.set(dbName, promisePool)
return promisePool
}