繁体   English   中英

重试连接postgres Nodejs

[英]Retry connection postgres Nodejs

我正在为我的 express web 服务器使用 postgres 数据库。 我正在使用“pg”库对该数据库执行查询。

这是我的连接方法:

const db = new Client({
    user: 'xxx',
    host: 'xxx',
    database: 'xxx',
    password: 'xxx',
    port: xxx,
})
db.connect(err => {
    if (err) {
        console.error('connection error', err.stack)
    } else {
        console.log('connected')
    }

然后执行一个请求,我这样做:

db.query(MY_REQUEST, function (err, data) {
            if (err) throw err;
            res.render('hello/world', {
                title: 'Hello',
                data: data.rows
            });
        });`

这一切都完美无缺。 但是在没有使用我的网站几分钟后,我与数据库的连接超时,并且出现以下错误:

node:events:355
throw er; // Unhandled 'error' event
       ^
Error: Connection terminated unexpectedly
at Connection.<anonymous> (/usr/src/app/node_modules/pg/lib/client.js:132:73)
at Object.onceWrapper (node:events:484:28)
at Connection.emit (node:events:378:20)
at Socket.<anonymous> (/usr/src/app/node_modules/pg/lib/connection.js:58:12)
at Socket.emit (node:events:378:20)
at TCP.<anonymous> (node:net:665:12)
Emitted 'error' event on Client instance at:
at Client._handleErrorEvent (/usr/src/app/node_modules/pg/lib/client.js:319:10)
at Connection.<anonymous> (/usr/src/app/node_modules/pg/lib/client.js:149:16)
at Object.onceWrapper (node:events:484:28)
[... lines matching original stack trace ...]
at TCP.<anonymous> (node:net:665:12)

当连接断开或请求失败时,如何自动重新连接?

您应该附加一个error处理程序,以防止未处理的错误使您的应用程序崩溃。 它很简单:

db.on('error', e => {
  console.error('DB error', e);
});

至于为什么会发生错误,我们需要更多详细信息,看起来可能是由于空闲超时导致的连接重置?

在继续主 function 之前,您可以创建 function 来控制是否连接到数据库。

创建一个 function 用于控制database connection statusreconnecting等,在运行与数据库相关的 function 之前,首先启动中间 function 并等待您再次使用数据库并继续使用数据库。

If you want(which should be prefered way mostly), create that middle function as an async function and return a promise , when using that function wait for that function .

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM