使用nodejs实现长轮询

时间:2012-07-25 16:19:40

标签: node.js real-time long-polling

我使用了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. 我应该在每次从DB查询后关闭连接,还是只有一次我回复?
  3. 我想优化并优化建议?

1 个答案:

答案 0 :(得分:0)

这取决于,nextTick通常更加充足,但从不同的角度考虑它,基本上你每秒都会对每个与你的长期投票有关的用户进行“短轮询”。

因此,即使您的网络服务器由于长轮询而没有进行不必要的民意调查(顺便说一句,是否还有退出条件以及空答案?)您仍然在短轮询数据库。

相关问题