我根据他们的示例为firebase设置了一个简单的在线用户数。问题是它依赖于删除断开连接的计数。但是,firebase似乎每两个月就会消失并删除ondisconnect处理程序。这意味着随着时间的推移,计数越来越多。有什么方法可以解决这个问题吗?
ty.Presence = function() {
this.rooms = {}
this.presence = fb.child('presence')
this.connectedRef = fb.child('.info/connected');
if (!localStorage.fb_presence_id) {
localStorage.fb_presence_id = Math.random().toString(36).slice(2)
}
this.browserID = localStorage.fb_presence_id
var first = false
}
ty.Presence.prototype.add = function(roomID, userobj) {
var self = this
var userListRef = this.presence.child(roomID)
// Generate a reference to a new location for my user with push.
var obj = {
s: "on",
id: this.browserID
}
if (userobj) {
obj.u = {
_id: userobj._id,
n: userobj.username
}
if (userobj.a) {
obj.u.a = userobj.a
}
}
var myUserRef = userListRef.push(obj)
this.rooms[roomID] = myUserRef
this.connectedRef.on("value", function(isOnline) {
if (isOnline.val()) {
// If we lose our internet connection, we want ourselves removed from the list.
myUserRef.onDisconnect().remove();
}
});
};
ty.Presence.prototype.count = function(roomID, cb) {
var self = this
var userListRef = this.presence.child(roomID)
var count = 0
function res () {
var usersArr = _.pluck(users, 'id')
usersArr = _.uniq(usersArr)
count = usersArr.length
if (cb) cb(count)
}
var users = {}
userListRef.on("child_added", function(css) {
users[css.name()] = css.val();
res()
});
userListRef.on("child_removed", function(css) {
delete users[css.name()]
res()
});
cb(count)
};
ty.Presence.prototype.get = function(ref) {
return this[ref]
};
ty.Presence.prototype.setGlobal = function(object) {
var self = this
_.each(this.rooms, function (myUserRef) {
myUserRef.set(object)
})
};
ty.Presence.prototype.remove = function(roomID) {
if (this.rooms[roomID])
this.rooms[roomID].remove();
};
ty.Presence.prototype.off = function(roomID) {
var userListRef = this.presence.child(roomID)
userListRef.off()
};
ty.presence = new ty.Presence()
ty.presence.add('all')
答案 0 :(得分:1)
如果重新启动Firebase,则onDisconnect处理程序可能会丢失(例如,当新版本被推送时)。一种简单的方法是在存储记录时将时间戳作为优先级附加到记录中。只要客户端保持在线状态,请让他偶尔更新时间戳。
setInterval(function() {
connectedRef.setPriority(Date.now());
}, 1000*60*60*4 /* every 4 hours */ );
因此,任何达到24小时的记录显然都是孤儿。客户端可能会遇到挑战(例如,当新客户端第一次收到列表时)或服务器进程(例如带有setInterval()的node.js脚本以检查早于X的记录)。
presenceRef.endAt(Date.now()-24*60*60*1000 /* 24 hours ago */).remove();
不太理想,当然,但我在应用程序中使用了功能性解决方法。