安裝
$ cd game-server
$ npm i --save mysql
配置
$ vim /game-server/config/mysql.json
{
"development": {
"host": "127.0.0.1",
"port": 3306,
"user": "root",
"password":"root",
"charset": "utf8mb4",
"database": "pomelo",
"connectionLimit": 10
},
"production": {
"host": "127.0.0.1",
"port": 3306,
"user": "root",
"password":"root",
"charset": "utf8mb4",
"database": "pomelo",
"connectionLimit": 10
}
}
配置參數(shù) | 描述 |
---|---|
host | 連接主機(jī) |
user | 用戶名 |
password | 密碼 |
database | 數(shù)據(jù)庫(kù) |
charset | 數(shù)據(jù)庫(kù)編碼 |
acquireTimeout | 獲取連接的毫秒數(shù) |
waitForConnections | 為true時(shí)表示連接排隊(duì)等待可用連接 |
connectionLimit | 單詞可創(chuàng)建最大連接數(shù)量 |
queueLimit | 連接池最大請(qǐng)求數(shù)量,0為無(wú)限制扒怖。 |
使用連接池時(shí)炼列,連接池并未初始化所有連接,當(dāng)需要操作數(shù)據(jù)庫(kù)時(shí)需要先使用pool.getConnection()
方法獲取連接對(duì)象突倍。獲取連接對(duì)象操作完成后建議使用connection.release()
方法主動(dòng)釋放連接。
封裝
$ vim game-server/utils/mysql.js
const mysql = require("mysql");
let Module = function(config){
if(!config){
console.error("mysql config is null");
return;
}
this.pool = mysql.createPool(config);
};
Module.prototype.query = function(sql, values){
return new Promise((resolve, reject)=>{
this.pool.getConnection((error, connection)=>{
if(error){
reject(error);
}else{
if(values){
connection.query(sql, values, (err, rows)=>{
if(err){
reject(err);
}else{
if(rows.length===1){
rows = rows[0];
}
resolve(rows);
}
});
}else{
connection.query(sql, (err, rows)=>{
if(err){
reject(err);
}else{
if(rows.length===1){
rows = rows[0];
}
resolve(rows);
}
});
}
connection.release();
}
});
});
};
module.exports = function(config){
return new Module(config);
};
使用
在入口文件app.js
中加載數(shù)據(jù)配置并設(shè)置mysql對(duì)象
$ vim app.js
app.configure("production|development", function(){
//加載數(shù)據(jù)庫(kù)配置
app.loadConfig("mysqlConfig", app.getBase()+"/config/mysql.json");
//初始化數(shù)據(jù)庫(kù)連接對(duì)象
const mysql = require(app.getBase()+"/utils/mysql.js");
app.set("mysql", mysql(app.settings.mysqlConfig));
});
加載配置文件
在app.js
入口文件中使用app.loadConfig(key, value)
方法加載game-server/config
文件夾下的任何JSON格式的配置文件盆昙。加載后的配置文件信息會(huì)被保存到app.setting
對(duì)象對(duì)應(yīng)key
的屬性中羽历。
$ vim game-server/app.js
app.configure("production|development", function(){
//加載數(shù)據(jù)庫(kù)配置
app.loadConfig("mysqlConfig", app.getBase()+"/config/mysql.json");
//獲取配置文件
console.log(app.settings.mysqlConfig);
});
訪問上下文變量
在應(yīng)用實(shí)例app
中具有針對(duì)上下文的getter/setter
方法用于獲取和設(shè)置變量。
app.set(name, value, [isAttach]);
setter
方法的第三個(gè)可選參數(shù)isAttach
表示是否作為應(yīng)用實(shí)例app
屬性附加淡喜。
app.get(name);
例如:設(shè)置并獲取MySQL秕磷,并執(zhí)行其query方法。
app.configure("production|development", async ()=>{
//加載數(shù)據(jù)庫(kù)配置
app.loadConfig("mysqlConfig", app.getBase()+"/config/mysql.json");
//初始化數(shù)據(jù)庫(kù)連接對(duì)象
const mysql = require(app.getBase()+"/utils/mysql.js");
app.set("mysql", mysql(app.settings.mysqlConfig));
//test
const sql = "SELECT * FROM game_user WHERE 1=1";
const result = await app.get("mysql").query(sql);
console.log(result);
});