码迷,mamicode.com
首页 > 其他好文 > 详细

基于express+redis高速实现实时在线用户数统计

时间:2017-06-11 14:19:44      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:clone   pack   ace   class   sorted   pre   作者   tor   pop   

  作者:zhanhailiang 日期:2014-11-09

本文将介绍怎样基于express+redis高速实现实时在线用户数统计。

1. 在github.com上创建项目uv-tj。将其同步到本地:

[root@~/wade/nodejs]# git clone git@github.com:billfeller/uv-tj.git

2. 使用npm init初始化node项目(本例不须要复杂的操作,所以暂不使用express工具来生成express应用程序骨架):

[root@~/wade/nodejs/uv-tj]# npm init

3. 向package.json加入应用程序启动命令。例如以下:

{
  "name": "uv-tj",
  "version": "1.0.0",
  "description": "uv tj demo",
  "main": "app.js",
  "scripts": {
    "start": "node app.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/billfeller/uv-tj.git"
  },
  "keywords": [
    "uv",
    "tj",
    "demo"
  ],
  "author": "billfeller",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/billfeller/uv-tj/issues"
  },
  "homepage": "https://github.com/billfeller/uv-tj",
  "dependencies": {
    "express": "^4.10.1",
    "redis": "^0.12.1"
  }
}

4. 加入app.js文件。代码例如以下:

// 创建express对象和一个redisclient连接
var express = require(‘express‘);
var redis = require(‘redis‘);
var db = redis.createClient();
var app = express();
 
// 纪录用户在线的中间件 
// 这里使用user-agent作为用户标识符
// 这里使用sorted sets,以便查询近期N毫秒内在线的用户;
app.use(function(req, res, next) {
    var ua = req.headers[‘user-agent‘];
    db.zadd(‘online‘, Date.now(), ua, next);
});
 
// 通过 zrevrangebyscore 来查询上一分钟在线用户。
// 我们将能得到从当前时间算起在 60,000 毫秒内活跃的用户。

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 (); }); });   // 从不同浏览器进入就能够看到同一时候在线用户数不断添加 app.get(‘/‘, function(req, res){ res.send(req.online.length + ‘ users online‘); });   app.listen(3000);

5. 启动应用程序:

[root@~/wade/nodejs/uv-tj]# npm start
 
> uv-tj@1.0.0 start /root/wade/nodejs/uv-tj
> node app.js

訪问结果例如以下:

技术分享

6. 总结:

使用此方法能够非常方便计算相似的统计量,如PV,UV。订单数等等。

个人觉得涉及计数器的需求都能够通过此方案来解决

7. 完整代码请见:

8. 推荐阅读:

基于express+redis高速实现实时在线用户数统计

标签:clone   pack   ace   class   sorted   pre   作者   tor   pop   

原文地址:http://www.cnblogs.com/jhcelue/p/6985010.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!