我在 nodejs 中有以下 postgresql 连接文件:
// postgresql.js
"use strict";
const { Pool } = require('pg');
module.exports = new Promise((resolve, reject) => {
const pool = new Pool({
host: '127.0.0.1',
port: 5432,
user: 'postgres',
password: 'postgres',
database: 'postgres',
connectionTimeoutMillis: 0,
idleTimeoutMillis: 0,
min: 10,
max: 20,
});
resolve({ pool });
});
我正在使用 promise ,因为稍后我将开始使用 Google Cloud Secret Manager . secret 是异步获取的,因此在服务器启动时无法建立数据库连接。在我的 Controller 文件中,我是这样使用它的:
// apicontroller.js
"use strict";
const postgresql = require('./postgresql');
app.get('/api/test', async (req, res, next) => {
// resolve the postgresql promise
const { pool } = await postgresql;
// resolve the pool.connect() promise
const client = await pool.connect();
// use the client object here
// eg. await client.query(...)
});
问题不在于它不起作用,相反,它就像一个魅力!但我在问自己:我是在重用连接池,还是在每次请求这条路由时都创建一个新的连接(池)?这是仅重用一次数据库连接的正确方法吗?
编辑:我只包含了相关的代码部分。
最佳答案
正如 node-postgres 的文档中所解释的那样, 我会用 pool.query
而不是使用(处理)client
.
Single query, If you don't need a transaction or you just need to run a single query, the pool has a convenience method to run a query on any available client in the pool. This is the preferred way to query with node-postgres if you can as it removes the risk of leaking a client.
所以我的代码会像;
postgresql.js
let mainPool = null;
functiona createPool(){
const pool = new Pool({
host: '127.0.0.1',
port: 5432,
user: 'postgres',
password: 'postgres',
database: 'postgres',
connectionTimeoutMillis: 0,
idleTimeoutMillis: 0,
min: 10,
max: 20,
});
return pool;
}
function getPool(){
if(!mainPool){
mainPool = createPool();
}
return mailPool;
}
export default { getPool };
Controller .js const { getPool } = require('./postgresql');
app.get('/api/test', async (req, res, next) => {
getPool().query('SELECT * FROM users', [], (err, res) => {
if (err) {
return res.status(500).send(err);
}
return res.status(500).send(res);
});
});
关于node.js - 在 nodejs 中重用 postgresql 连接池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64848920/