我实现了类似社交网络的通知,使用带有 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();
})
}
};
这是我的问题:
- 我在这里使用 setTimeout,是否合适?也许使用 nextTick 或 setInterval?
- 我应该在每次从数据库查询后关闭连接,还是只在我回复一次时关闭连接?
- 我想优化,优化建议?