在启动 Node/Express Server 之前连接到 MySQL



我是Node新手,并尝试将mysql2/promises合并到我的 Node (8.3.0(/Express (4.17( 应用程序中,但在启动服务器之前很难确定如何设置连接池。

配置.js

module.exports = Object.freeze({
DB_HOSTNAME: process.env.DB_HOSTNAME,
DB_PORT: process.env.DB_PORT || 3306,
DB_NAME: process.env.DB_NAME,
DB_USERNAME: process.env.DB_USERNAME,
DB_PASSWORD: process.env.DB_PASSWORD,
SSL_CERT: process.env.SSL_CERT || './ssl/server.crt',
SSL_KEY: process.env.SSL_KEY || './ssl/server.key',
SERVER_PORT: process.env.SERVER_PORT || 443,
STATIC_DIR: '/static'
});

应用.js

const fs = require('fs');
const express = require('express');
const app = express();
const config = require('./config');
const mysql = require('mysql2/promise');
const dbConfig = {
connectionLimit: 10,
host: config.DB_HOSTNAME,
user: config.DB_USERNAME,
password: config.DB_PASSWORD,
database: config.DB_NAME,
ssl: 'Amazon RDS'
};
const sslConfig = {
key: fs.readFileSync(config.SSL_KEY),
cert: fs.readFileSync(config.SSL_CERT)
};
const server = require('https').createServer(sslConfig, app);
// Start web server
server.listen(config.SERVER_PORT, () => {
console.log('Web server started on port ' + config.SERVER_PORT);
});
app.use(express.static(__dirname + config.STATIC_DIR));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});

我需要在异步/等待函数中调用mysql.createPool(dbConfig)吗?

您可以使用以下代码在mysql2-promise中建立池连接:

var db = require('mysql2-promise')();
db.configure({
"host": "localhost",
"user": "foo",
"password": "bar",
"database": "db"
});
db.pool.on('connection', function (poolConnection) {
poolConnection.config.namedPlaceholders = true;
});
db.execute('SELECT * FROM users WHERE LIMIT = :limit', {limit: 10}).spread(function (users) {
console.log('Hello users', users);
});

使用时mysql模块中,应调用creatPool进行连接

mysql模块示例

var mysql = require('mysql');
var pool  = mysql.createPool({
connectionLimit : 10,
host            : 'example.org',
user            : 'bob',
password        : 'secret',
database        : 'my_db'
});
pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});

相关内容

  • 没有找到相关文章

最新更新