Postgresql Error: connection terminated

痞子三分冷 提交于 2021-01-27 10:44:24

问题


i have a simple application linked up to a postgres database. it reads about 30 rows of data when you load up the application. but every now an then it wont load and when i look at my server i have the error Error: connection terminated.

usually if i load it up several times in a short space of time.

does anyone know why this might be happening? am i working it too hard?

the code is below:

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

        })
    }

回答1:


I ran into the same "Error: Connection terminated" error on a Node method that was inserting rows into a Postgres database. Here's how I was able to fix it.

The console error was not very helpful, so I looked at the Postgres logs. (using a 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

This means that the client somehow dropped the connection before the server could finish. In my case, I did not call my asynchronous methods correctly so the client finished before the database statement could be executed and client dropped the DB connection. I used the async/await style Node methods and I forgot to call my async method with await, which caused the error.

Be sure to follow one of these examples for Postgres queries in Node.




回答2:


It looks like you're using node-postgres. You should consider using its connection pooling. From the documentation:

"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."

There is a lot going on when creating a new connection and you should look to avoid it when possible. Taking advantage of pooling could help in your situation.



来源:https://stackoverflow.com/questions/36685117/postgresql-error-connection-terminated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!