Wednesday, January 13, 2016

Redis+PHP: 实时统计在线用户数



https://github.com/jifei/BeautifulPHP/blob/master/Algorithm/OnlineUser.php
 * 每分钟百万用户,实时统计最近15分钟在线用户总数
 * 使用redis的set数据结构,把用户ID或者唯一表示的其他属性存放在当前分钟的集合中
 * 计算指定时间段内的用户数,计算这些分钟集合的并集即可,性能在2s内
 *
 * 优化:集合设置过期时间,集合的key可以增加日期date('dhi'),查看在线用户数增加开始结束时间判断限制
class OnlineUser
{
    public $prefix_key = "online";//key前缀
    public function __construct()
    {
        $this->redis = new Redis();
    }
    /**
     * 往集合中添加新的在线用户
     *
     * @param $uid
     */
    public function addUser($uid)
    {
        $this->redis->sAdd($this->prefix_key . date('hi'), $uid);
    }
    /**
     * 获取在线用户数
     *
     * @param $start_min  统计开始分钟 hi格式
     * @param $end_min    统计结束的分钟
     *
     * @return mixed
     */
    public function userNum($start_min, $end_min)
    {
        //第一个参数,并集的key名称
        $params[] = $this->prefix_key . $start_min . '_' . $end_min;
        //遍历时间区间内所有的分钟,并放入到参数中
        for ($min = $start_min; $min < $end_min; $min++) {
            $params[] = $this->prefix_key . $min;
        }
        //求所有分钟的用户的并集并保存,性能比直接计算返回快很多,省去了数据传输
        $num = call_user_func_array([$this->redis, "sUnionStore"], $params);
        //删除临时并集
        $this->redis->delete($params[0]);
        return $num;
    }
}

http://laoxu.blog.51cto.com/4120547/1318461
python操作在线用户数的简单代码:
1
2
3
4
5
6
7
8
9
#!/usr/bin/python
import redis
r=redis.StrictRedis(host='192.168.39.138',port=6379)
r.set('online','0')
r.incr('online')
r.incr('online')
r.incr('online')
r.decr('online')
print r.get('online')
如果有新的用户登录incr插入一条记录,如果有用户下线可以使用decr或者规定一个超时时间,对不活跃的用户自动删除记录。
http://blog.csdn.net/billfeller/article/details/40960613
// 纪录用户在线的中间件 
// 这里使用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');
});

Labels

Review (572) System Design (334) System Design - Review (198) Java (189) Coding (75) Interview-System Design (65) Interview (63) Book Notes (59) Coding - Review (59) to-do (45) Linux (43) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (31) Big Data (29) Product Architecture (28) MultiThread (27) Soft Skills (27) Concurrency (26) Cracking Code Interview (26) Miscs (25) Distributed (24) OOD Design (24) Google (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) System Design - Practice (20) Tips (19) Algorithm (17) Company - Facebook (17) Security (17) How to Ace Interview (16) Brain Teaser (14) Linux - Shell (14) Redis (14) Testing (14) Tools (14) Code Quality (13) Search (13) Spark (13) Spring (13) Company - LinkedIn (12) How to (12) Interview-Database (12) Interview-Operating System (12) Solr (12) Architecture Principles (11) Resource (10) Amazon (9) Cache (9) Git (9) Interview - MultiThread (9) Scalability (9) Trouble Shooting (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Cassandra (8) Company - Uber (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Design (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Mac (7) Machine Learning (7) NoSQL (7) C++ (6) Chrome (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Python (5)

Popular Posts