Postgresql Error: connection terminated

Postgresql Error: connection terminated

我有一个连接到 postgres 数据库的简单应用程序。当您加载应用程序时,它会读取大约 30 行数据。但时不时地它不会加载,当我查看我的服务器时我有错误错误:连接终止。

通常如果我在短 space 的时间内多次加载它。

有谁知道为什么会这样?我是不是太努力了?

代码如下:

    function getDB(callback){
        console.log('inside getDB')
        Client.connect(function(err){
            if(err){
                return console.log('connection error', err)
            }
            Client.query('SELECT * FROM gallery', function(err, result){
                if(err){
                    return console.log('error receiving data', err)
                } else{
                callback(null, result.rows)
                }
                Client.end()
            })

        })
    }

您似乎在使用 node-postgres。您应该考虑使用它的连接池。来自文档:

"Generally you will access the PostgreSQL server through a pool of clients. A client takes a non-trivial amount of time to establish a new connection. A client also consumes a non-trivial amount of resources on the PostgreSQL server - not something you want to do on every http request. Good news: node-postgres ships with built in client pooling."

创建新连接时会发生很多事情,您应该尽可能避免它。利用合并可能对您的情况有所帮助。

我 运行 在将行插入 Postgres 数据库的节点方法上出现相同的“错误:连接终止”错误。这是我修复它的方法。

控制台错误不是很有帮助,所以我查看了 Postgres 日志。 (使用 Mac)

$ tail -10 /usr/local/var/log/postgres.log 
2019-02-24 10:06:38.920 CST [58520] LOG:  could not receive data from client: Connection reset by peer
2019-02-24 10:06:38.921 CST [58520] LOG:  unexpected EOF on client connection with an open transaction

这意味着客户端在服务器完成之前以某种方式断开了连接。在我的例子中,我没有正确调用我的异步方法,所以客户端在数据库语句可以执行之前完成并且客户端断开了数据库连接。我使用了 async/await 样式的 Node 方法,但我忘记使用 await 调用我的异步方法,这导致了错误。

对于 Node 中的 Postgres 查询,请务必遵循其中一项examples