ECONNRESET连续两次查询数据库时写入错误[Node.js]

时间:2014-08-05 21:58:03

标签: javascript node.js postgresql heroku econnreset

我有一个node.js文件,其中包含从myoku postgresql数据库读取和写入的方法。我正在使用' pg'模块以访问DB。我的问题是连续多次调用我的getSleepMode函数会导致ECONNRESET错误。此函数只是向我的数据库发送查询并检索整数。我理解这可能是因为node.js函数是非阻塞的,并且getSleepMode()的两个实例都试图同时访问我的数据库。但是,如果多个客户端同时尝试从我的数据库获取数据,那么这不会成为一个问题吗?假设我的heroku postgresql数据库可以同时处理来自多个客户端的查询,这不应该仍然有效吗?我有以下代码的相关部分:

    [database connection variables omitted]

    var pg = require("pg")
    var conString = "pg://" + USER + ":" + PW + "@" + HOST + ":" + PORT + "/" + 
         DATABASE + "?ssl=true";

    var client = new pg.Client(conString);

     /*This function accesses my database and retrieves an integer field 
      called "sleepmode"*/

    function getSleepMode(username) {

       var query = "SELECT sleepmode FROM \"Users\" where username='" + 
                    username + "';";

       connectWrapper(query, function(err,result) {
           if (err) {
                return console.err("Error getting sleep mode", err);
           } 

           client.end();
           console.log("sleepmode " + result.rows[0].sleepmode);
       });
   }


       /*This function is here so I can reuse it for more than just  
        my getSleepMode() function*/

      function connectWrapper(query, handler) {

         client.connect(function(err) {
           if (err) { 
            return console.error('could not connect to postgresq',err);
           }
           client.query(query, handler);
         });
      }

     getSleepMode("username1");  //This ALONE works
     getSleepMode("username2");  //but when this line follows, i get the error

运行此操作会导致此输出:

$user: node dbconnect.js
could not connect to postgresq { [Error: write ECONNRESET] code: 'ECONNRESET', err
ECONNRESET', syscall: 'write' }
could not connect to postgresq { [Error: write ECONNRESET] code: 'ECONNRESET', err
ECONNRESET', syscall: 'write' }

Events.js:72
       throw er; // Unhandled 'error' event
         ^
Error: write ECONNRESET
   at errnoException (net.js:904:11)
   at Socket._write (net.js:645:26)
   at doWrite (_stream_writable.js:225:10)
   at writeOrBuffer (_stream_writable.js:215:5)
   at Socket.Writable.write (_stream_writable.js:182:11)
   at Socket.write (net.js:615:40)
   at write (_stream_readable.js:601:24)
   at flow (_stream_readable.js:610:7)
   at _stream_readable.js:578:7
   at process._tickCallback (node.js:419:13)

但是当我运行它以便只调用一次getSleepMode()时,没有错误并且它按预期工作。

$user: node dbconnect.js
sleepmode 1

1 个答案:

答案 0 :(得分:0)

您要两次结束客户端(client.end();),这可能会导致您的问题。具体来说,看起来连接在另一个查询完成执行之前就已关闭。