inint
This commit is contained in:
46
module/server/mysql/gameDB.js
Normal file
46
module/server/mysql/gameDB.js
Normal 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
|
||||
}
|
||||
Reference in New Issue
Block a user