簡體   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