0

我实现了类似社交网络的通知,使用带有 nodeJs 的长轮询

数据库,我正在使用 redis 和 cassandra

我在redis中将时间戳保存为“user_read”

每次用户阅读通知时,我都会刷新“user_read”

当数据库收到通知时间戳大于“user_read”时

我会回复用户

我的代码是这样的

function(req, res){
longPoll()
function longPoll(){
    async.waterfall([
         connectDB,
         getNotification             
],function(err,data){
    if(there's no notification timestamp larger than user_read){
          setTimeout(longPoll, 1000);
    }else if(there's new data){
          res.json(data);
    }

    if(con)
       con.close();
})
}
};

这是我的问题:

  1. 我在这里使用 setTimeout,是否合适?也许使用 nextTick 或 setInterval?
  2. 我应该在每次从数据库查询后关闭连接,还是只在我回复一次时关闭连接?
  3. 我想优化,优化建议?
4

1 回答 1

0

这取决于,nextTick 通常更合适,但从不同的角度考虑它,基本上你每秒都在为连接到你的长轮询的每个用户“短轮询”数据库。

因此,即使您的网络服务器由于长轮询而没有获得不必要的轮询(顺便说一句,您是否也有一个空答案的退出条件?)您仍然在短轮询数据库。

于 2012-07-25T16:28:31.917 回答