【问题标题】:node-postgres, Connection terminated unexpectedlynode-postgres,连接意外终止
【发布时间】:2018-09-16 17:38:46
【问题描述】:

我正在尝试使用 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查询的问题,并续集

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

【问题讨论】:

标签: javascript node.js sequelize.js node-postgres


【解决方案1】:

我开始遇到同样的问题,但只有长时间查询,我通过在 Pool 构造函数中设置 idleTimeoutMillis 找到了可能的解决方案,例如设置为 20000(默认值为 10000)

https://node-postgres.com/api/pool#new-pool-config-object-

【讨论】:

    【解决方案2】:

    使用 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'}});
    

    【讨论】:

      【解决方案3】:

      处理可能需要数小时的流程,我使用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,
      });
      

      【讨论】:

        【解决方案4】:

        上述所有解决方案都对我不起作用。我通过互联网搜索但没有找到任何合适的解决方案。最后我发现我在pg客户端输入了错误的端口号。

        这是我找到实际端口号的地方: 服务器 > 数据库 > 属性

        这是在我的代码中输入的。问题解决了

        【讨论】:

          【解决方案5】:

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

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

          【讨论】:

            【解决方案6】:

            我做了很多研究来解决这个问题。这些pg 配置解决了我的问题

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

            【讨论】:

              【解决方案7】:

              试试这个:

              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!");
              });
              

              【讨论】:

                猜你喜欢
                • 2022-12-14
                • 2020-05-10
                • 1970-01-01
                • 2016-05-14
                • 2021-10-10
                • 1970-01-01
                • 1970-01-01
                • 2018-03-03
                • 1970-01-01
                相关资源
                最近更新 更多