目前,我没有在我的设置中使用连接池,因为我的应用程序中只有 1-4 个用户。
根据doc这是推荐的方式。
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
现在,我所做的就是导出连接对象并将其共享给其他 api 资源。
在db.js文件上
var mysql = require('mysql');
var connection = mysql.createConnection({ ... });
module.exports = connection;
在 api.js 文件上
const express = require('express');
const router = express.Router();
const conn = require('./db');
router.post('/create', function (req, res) {
connection.query('INSERT ...', function (error, results, fields) {
if (error) throw error;
// connected!
});
});
router.post('/update', function (req, res) {
connection.query('UPDATE SET ...', function (error, results, fields) {
if (error) throw error;
// connected!
});
});
等等这些示例中省略的其他 api 资源也是如此。
这种连接设计有什么缺点?
最佳答案
如有错误,请指正。我认为,即使您导出连接对象,您仍然在一一管理连接。
Opening and maintaining a database connection for each user, especially requests made to a dynamic database-driven website application, is costly and wastes resources Wikipedia
并且来自相同的 doc ,
This is because two calls to pool.query() may use two different connections and run in parallel
所以最好的方法是使用池来管理连接
Connections are lazily created by the pool. If you configure the pool to allow up to 100 connections, but only ever use 5 simultaneously, only 5 connections will be made. Connections are also cycled round-robin style, with connections being taken from the top of the pool and returning to the bottom.
希望有帮助。
关于javascript - 在node-express应用程序中使用node-mysql建立共享连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49727972/