首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >node-postgres,连接意外终止

node-postgres,连接意外终止
EN

Stack Overflow用户
提问于 2018-04-07 00:18:42
回答 7查看 18.1K关注 0票数 5

我正在尝试使用node-postgres连接到远程数据库。

我可以使用psql客户端进行连接,但在尝试运行此命令时(使用与psql客户端相同的连接字符串),我得到了错误Connection terminated unexpectedly

代码语言:javascript
复制
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

EN

回答 7

Stack Overflow用户

发布于 2019-03-12 10:41:42

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

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

票数 3
EN

Stack Overflow用户

发布于 2018-04-12 04:08:13

使用pg:

代码语言:javascript
复制
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());

序列化:

代码语言:javascript
复制
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'}});
票数 1
EN

Stack Overflow用户

发布于 2020-06-08 23:24:06

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

代码语言:javascript
复制
const { Pool } = require('pg')

const pool = new Pool({
  user: 'postgres',
  host: 'localhost',
  database: 'my_database',
  password: 'XXXX',
  port: 5423,
  idleTimeoutMillis: 0,
  connectionTimeoutMillis: 0,
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49697082

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档