![](/img/trans.png)
[英]About MySQL module in node.js and concurrent connections to mySQL Database
[英]Managing database connections in Node.js, best practices?
我正在構建一個 Node 應用程序,它將查詢簡單和更復雜(多個連接)的查詢。 我正在尋找有關如何管理 mySQL 連接的建議。
我有以下要素:
//this is router1 router.get('/', function (req, res){ connection.connect(function(Err){...}); connection.query('SELECT* FROM table WHERE id = "blah"', function(err,results,fields){ console.log(results); }); ... connection.end(); })
我是否應該在每次請求“/router1/”時連接到 mysql,就像在這個例子中一樣,還是最好在啟動時保持一個連接打開? 作為:
connection.connect();在外面:
router.get('/',function(req,res){... });?
我為此使用 mysql2,它基本上是 mysql,但有承諾。 如果你使用 mysql 你也可以這樣做。
創建一個名為 connection.js 之類的單獨文件。
const mysql = require('mysql2');
const connection = mysql.createPool({
host: "localhost",
user: "",
password: "",
database: ""
// here you can set connection limits and so on
});
module.exports = connection;
然后最好創建一些模型並從控制器中調用它們,在router.get('/', (req, res) => {here});
一個模型看起來像這樣:
const connection = require('../util/connection');
async function getAll() {
const sql = "SELECT * FROM tableName";
const [rows] = await connection.promise().query(sql);
return rows;
}
exports.getAll = getAll;
你可以在有或沒有承諾的情況下做到這一點,這並不重要。 查詢完成后,您與池的連接將自動釋放。 然后你應該從你的路由器或應用程序調用 getAll 。
我希望這有幫助,如果沒有,抱歉。
連接池是應該如何完成的。 為每個請求打開一個新連接會減慢應用程序的速度,它遲早會成為瓶頸,因為節點不會像 PHP 那樣自動關閉連接。 因此,連接池確保固定數量的連接始終可用,並在需要時處理關閉不必要的連接。
這就是我使用 Sequelize 啟動我的 Express 應用程序的方式。 對於 Mongoose,除了庫 API 外,它或多或少是相似的。
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mysql',
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
});
sequelize.authenticate()
.then(
// On successfull connection, open a port
// and listen to requests. This is where the application
// starts listening to requests.
() => {
const server = http.createServer(app);
server.listen(port);
},
)
.catch(err => {
console.error('Unable to connect to the database:', err);
console.error('Cancelling app server launch');
});
該應用程序僅在建立數據庫連接后啟動。 這確保服務器在沒有任何數據庫連接的情況下不會處於活動狀態。 連接池將默認保持連接打開,並使用池外的連接進行所有查詢。
如果您使用createPool
mysql
將管理打開和關閉連接,您將獲得更好的性能。 用mysql
還是mysql2還是sequlize都沒關系。 為createPool
使用單獨的文件並將其導出。 您可以在任何地方使用它。 不要使用類,只是在功能上使用它以獲得更好的 nodejs 性能。
> npm install mysql
mysql 是一個很棒的模塊,它使使用 MySQL 變得非常容易,並且它提供了您可能需要的所有功能。
一旦你安裝了 mysql,你所要做的就是連接到你的數據庫
var mysql = require('mysql')
var conn = mysql.createConnection({
host: 'localhost',
user: 'username',
password: 'password',
database: 'database'
})
conn.connect(function(err) {
if (err) throw err
console.log('connected')
})
現在您已准備好開始寫入和讀取數據庫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.