保持连接打开?

Joe*_*Joe 2 postgresql node.js express

我使用节点js,express和postgresql作为后端.这是我用来制作rest API的方法:

exports.schema = function (inputs, res) {
  var query = knex('schema')
    .orderBy('sch_title', 'asc')
    .select();

  query.exec(function (err, schemas) {
    if(err){
      var response = {
        message: 'Something went wrong when trying to fetch schemas',
        thrownErr: err
      };
      console.error(response);
      res.send(500, response);
    }
    if(schemas.length === 0){
      var message = 'No schemas was found';
      console.error(message);
      res.send(400, message);
      return;
    }
    res.send(200, schemas);
  });
};
Run Code Online (Sandbox Code Playgroud)

它工作但过了一段时间postgres记录错误,它不再工作:

sorry, too man clients already
Run Code Online (Sandbox Code Playgroud)

我是否需要以某种方式关闭每个请求?在快递文档中找不到任何相关内容.有什么不对?

此错误仅发生在生产服务器上.不在开发机器上.

更新 应用程序仅在一个"模块"中制动.应用程序的其余部分工作正常.因此,只有一些查询会产生错误.

hyu*_*ubs 5

只需为整个应用程序打开一个连接即可.该文档显示了一个示例如何做到这一点.

这段代码在你的app.js...

var Knex  = require('knex');
Knex.knex = Knex.initialize({
  client: 'pg',
  connection: {
    // your connection config
  }
});
Run Code Online (Sandbox Code Playgroud)

当你想在控制器/中间件中查询时......

var knex = require('knex').knex;

exports.schema = function (req, res) {
    var query = knex('schema')
        .orderBy('sch_title', 'asc')
        .select();
    // more code...
};
Run Code Online (Sandbox Code Playgroud)

如果你放在Knex.initialize一个app.use或者里面app.VERB,它会被重复调用每个请求,因此你最终会多次连接到PG.

对于大多数情况,您不需要为每个HTTP请求执行open + query + close.