0

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

    [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
4

1 回答 1

0

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

于 2014-08-06T00:29:34.303 回答