活跃用户统计

一,功能背景

  领导偶然间问起我们的考核系统使用情况如何,最近考虑下做个活跃用户统计功能

二,功能设计

  针对性能上要求实时统计,用户名都为8位数字等特点,拟采用redis方案:

  使用bitmap,用户登录的同时,将用户所在的位置为1

三,代码

  1,直接上代码

  

public void setUserActive(Integer id) {
          Date currentTime = new Date();
          String currentStr = new SimpleDateFormat("yyyy-MM-dd").format(currentTime);
          String key = "login:"+currentStr;
          try {
              cluster.setbit(key, id, true);
          } catch (Exception e) {
              log.error("登录激活用户计数出错:"+id+","+e);
          }
}

  用户登录的功能模块调用该方法,bitmap按照日期创建,即每天创建一个,垃圾回收委托给redis的GC机制。

  行内用户是8位数字,所以支持千万级的用户统计,经测试,性能较好。如果用户名非数字,可以通过哈希算法转换,本人暂未测试。

 2,统计

  

public long getActiveUserCount(int period) {
        Date currentTime = new Date();
        long bitCount = 0;
     SimpleDateFormat sf = new SimpelDateFormat("yyyy-MM-dd");
        try {
            for (int i = 0; i < period; i++) {
                //获得前一天的日期
                String currentStr = sf.format(currentTime);
                String key = "login:" + currentStr;
                //获得这一天日期的活跃用户字节数组
                bitCount += cluster.bitcount(key, 1, 99999999);
                currentTime = DateUtils.addDays(currentTime, -1);
            } 
        } catch (Exception e) {
            log.error("查询"+day+"天内活跃用户出错!"+e);
            return 0;
        }
        //统计人数
        return bitCount;
    }

  其中period指统计周期,我统计的是一周,传参为7,

  bicount方法后两位参数是start和end,在该范围内统计1的个数。这样就实现了活跃用户统计

猜你喜欢

转载自www.cnblogs.com/superchong/p/11128451.html