基於express+redis快速實現即時線上使用者數統計,expressredis

來源:互聯網
上載者:User

基於express+redis快速實現即時線上使用者數統計,expressredis

  作者: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對象和一個redis用戶端串連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. 完整代碼請見:

  • https://github.com/billfeller/uv-tj

8. 推薦閱讀:

  • http://www.expressjs.com.cn/guide.html#users-online

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.