Created
August 31, 2012 05:33
-
-
Save tj/3549368 to your computer and use it in GitHub Desktop.
users online with redis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var redis = require('redis'); | |
var db = redis.createClient(); | |
var app = express(); | |
// track users online (replace UA string with user id) | |
app.use(function(req, res, next){ | |
var ua = req.headers['user-agent']; | |
db.zadd('online', Date.now(), ua, next); | |
}); | |
// fetch the users online in the last minute | |
app.use(function(req, res, next){ | |
var min = 60 * 1000; | |
var ago = Date.now() - min; | |
db.zrevrangebyscore('online', '+inf', ago, function(err, users){ | |
if (err) return next(err); | |
req.online = users; | |
next(); | |
}); | |
}); | |
// route | |
app.get('/', function(req, res){ | |
res.send(req.online.length + ' users online'); | |
}); | |
app.listen(3000); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "app", | |
"version": "0.0.1", | |
"dependencies": { | |
"express": "3.x", | |
"redis": "*" | |
} | |
} |
@bobrik good point hahahha, fail
@visionmedia 404 on that guide link (well, the guide is there, the section isn't :-))
@rubenv hmm works for me
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
guide writeup for this example http://expressjs.com/guide.html#users-online