-
-
Save vothanhkiet/884bb242651178c227b83450c4c96080 to your computer and use it in GitHub Desktop.
users online with redis
This file contains hidden or 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 hidden or 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": "*" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment