node-postgres,连接意外终止

edqdpe6u  于 2022-12-18  发布在  Node.js
关注(0)|答案(9)|浏览(221)

我正在尝试使用node-postgres连接到远程数据库。
我可以使用psql客户端进行连接,但在尝试运行此命令时收到错误Connection terminated unexpectedly(使用与psql客户端相同的连接字符串):

const { Pool, Client } = require('pg')
const connectionString = '...'

const pool = new Pool({
  connectionString: connectionString,
})

pool.query('SELECT NOW()', (err, res) => {
  console.log(err, res)
  pool.end()
})

const client = new Client({
  connectionString: connectionString,
})
client.connect()

client.query('SELECT NOW()', (err, res) => {
  console.log(err, res)
  client.end()
})

我也一直在尝试与Sequelize ORM连接,但得到了同样的错误。
@编辑
使用本机模式修复了使用pg和sequelize进行客户端查询的问题
const { Pool, Client } = require('pg').native

c0vxltue

c0vxltue1#

我开始遇到同样的问题,但只是针对长时间查询,我找到了一个可能的解决方案,方法是在Pool构造函数中设置idleTimeoutMillis,例如设置为20000(默认值为10000)
请参见https://node-postgres.com/api/pool#new-pool-config-object-

czfnxgou

czfnxgou2#

处理可能需要几个小时的进程时,我找到了使用Pool但将idleTimeoutMillisconnectionTimeoutMillis都设置为0的解决方案。

const { Pool } = require('pg')

const pool = new Pool({
  user: 'postgres',
  host: 'localhost',
  database: 'my_database',
  password: 'XXXX',
  port: 5423,
  idleTimeoutMillis: 0,
  connectionTimeoutMillis: 0,
});
cig3rfwq

cig3rfwq3#

以上所有的解决方案都不适合我,我在网上搜索,但没有找到任何合适的解决方案,最后,我发现我在pg客户端输入了错误的端口号。
这是我找到我的实际端口号的地方:第一个月第一个月〉第一个月第二个月〉第一个月第三个月第一个月
并在我的代码中更新了它。问题就解决了

8iwquhpp

8iwquhpp4#

使用pg:

import pg from 'pg';  

const conStringPri = `postgres://${username}:${password}@${host}/postgres`;
  const Client = pg.Client;
  const client = new Client({connectionString: conStringPri});
  client.connect();

  client.query(`CREATE DATABASE ${dataBaseName}`)
    .then(() => client.end());

续集:

const sequelize = new Sequelize(dbName, username, password, {
  host: host || 'localhost',
  dialect: type || 'postgres',
  operatorsAliases,
  pool: {
    max: 5,
    min: 0,
    idle: 300000,
    acquire: 300000
  },
  port: port || 5432,
  logging: log => console.log('logging:', log)
});

const models = {};
// read all models from same folder
glob.sync(path.join(__dirname, '**/*.js'))
  .forEach(file => {
    const model = sequelize.import(file);
    models[model.name] = model;
  });

Object.keys(models).forEach(model => {
  if (models[model].associate) {
    models[model].associate(models);
  }
});

models.user.create(userObject);
models.user.findAll({where: {name: 'john'}});
lztngnrs

lztngnrs5#

我第一次使用Postgres时遇到这个错误。我不知道Postgres的默认端口是5432。在我的DB节点配置中将端口更改为5432解决了这个问题。

const db = knex({
    client: 'postgres',
        connection: {
            host: 'localhost',
            user: 'postgres',
            password: 'admin4321',
            database: 'postgres',
            port: 5432,
        }
    })
iqjalb3h

iqjalb3h6#

我做了大量的研究来解决这个问题,这些pg配置解决了我的问题

acquireConnectionTimeout: 5000,
  pool: {
    min: 0,
    max: 10,
    createTimeoutMillis: 8000,
    acquireTimeoutMillis: 8000,
    idleTimeoutMillis: 8000,
    reapIntervalMillis: 1000,
    createRetryIntervalMillis: 100,
  },
cxfofazt

cxfofazt7#

这可能与最小池大小设置为大于0的数字有关。
即使连接被终止,连接池也会保持最小的连接数。将最小连接数指定为0,并定义一个合适的空闲超时值(可能是1-5分钟),可以防止这种情况发生。
这在knex的一期杂志上有讨论。

rwqw0loc

rwqw0loc8#

//I have tried this problem is asynchronous property of javascript the connection is being ended before execution of query.
//This code below is working try this

const express = require("express")
const app = express()
const logger = require("morgan");
const {Client} = require("pg")
const Pool = require("pg").Pool
//pool for table queries

const pool = new Pool({
    user: 'postgres',
    password: process.env.PSQL_PASSWORD,
    host: "localhost",
    port: process.env.DBPORT,
    database: 'resume'
})

//middlewares
app.use(logger('dev'));
app.use(express.json());

//client1 for creating database
const client1 = new Client({
    host: 'localhost',
    user: 'postgres',
    password: process.env.PSQL_PASSWORD,
    port: process.env.DBPORT
})

//client2 for table
const client2 = new Client({
    host: 'localhost',
    user: 'postgres',
    password: process.env.PSQL_PASSWORD,
    port: process.env.DBPORT,
    database: 'resume'
})
//DB
const createDB = async () => {
    try {
        await client1.connect();
        console.log("creating db")
        await client1.query("create database resume;")
        console.log("created db")
    }
    catch (err) {
        console.log("Already created")
    }
    finally {
        await client1.end();
    }
}
//TABLE
const createTable = async () => {
    try {
        await client2.connect()
        console.log("creating Table")

        await client2.query(`create table resume(
            data jsonb
        )`)
        console.log("created Table")
    }
    catch (err) {
        console.log("Table already created")
    }
    finally {
        await client2.end()
    }
}
//port
app.listen(PORT, async () => {
    console.log(`Running at port ${PORT}...`)
    await createDB()
    await createTable()
})
pdtvr36n

pdtvr36n9#

试试这个:

var pg = require('pg');
const client = new pg.Client(
{
    user: 'username',
    host: 'host',
    database: 'myDb',
    password: 'secretPswd',
    port: portnum,
});
client.connect(function (err){
    if(err)
        console.log(err);
    else
        console.log("Connected!");
});

相关问题