Files
chuanqi-qycq-web/module/server/mysql/gameDB.js
艾贤凌 6d4a72161f inint
2026-03-16 12:05:55 +08:00

47 lines
1.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 游戏区服动态数据库连接工具
*
* 游戏每个区服对应独立的数据库 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
}