简体   繁体   English

重试连接postgres Nodejs

[英]Retry connection postgres Nodejs

I am using a postgres database for my express web server.我正在为我的 express web 服务器使用 postgres 数据库。 I am using the 'pg' library to execute queries on this database.我正在使用“pg”库对该数据库执行查询。

Here is my connection method:这是我的连接方法:

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')
    }

Then to execute a request I do this:然后执行一个请求,我这样做:

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

It all works perfectly.这一切都完美无缺。 But after several minutes without using my website, my connection to the db times out, and I get the following error:但是在没有使用我的网站几分钟后,我与数据库的连接超时,并且出现以下错误:

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)

How could I do to reconnect automatically when the connection is cut or when a request fails?当连接断开或请求失败时,如何自动重新连接?

You should attach an error -handler in order to prevent the unhandled error crashing your app.您应该附加一个error处理程序,以防止未处理的错误使您的应用程序崩溃。 It's as simple as:它很简单:

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

As to why the error happens we need more details, looks like it could be a connection reset due to idle-timeout?至于为什么会发生错误,我们需要更多详细信息,看起来可能是由于空闲超时导致的连接重置?

You can create a function to control if you're connected to database or not, before you continue with your main function.在继续主 function 之前,您可以创建 function 来控制是否连接到数据库。

Create a function for controlling database connection status , reconnecting etc. and before you run a database related function, first start that middle function and wait for result, after that you can continue using database again.创建一个 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 . 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