怎么统计 20 亿用户的登录状态 | bitmap

统计 20 亿用户的登录状态

用 redis 的 bitmap 结构。(一位只占 1 bit)

  • key:user_login_status

  • offset: uid

user 1024 登录时:setbit user_login_status 1024 1

user 1024 退出时:setbit user_login_status 1024 0

判断用户是否在线:getbit user_login_status 1024

统计在线用户人数bitcount user_login_status

拓展:如果获取已登录且手机为 ios 的数量

  • 新 key:user_ios

  • offset:uid

将 user_login_status 和 user_ios 进行 & 操作,获得一个新的 key:temp_user_login_ios,然后使用 bitcount temp_user_login_ios 进行计算。

实现 bitMap 类:

class BitMap {

    private byte[] byteBits;
    private int capacity;
    private int maxValue;

    public BitMap(int maxValue) {
        this.maxValue = maxValue;
        this.capacity = (maxValue / 8) + 1;
        byteBits= new byte[this.capacity];
    }

    public byte[] getByteBits() {
        return byteBits;
    }

    public int setStatus(int offset) {
        int index = offset / 8; // 找到在哪个 byte 位
        int position = offset % 8; // 找到在 byte 的第几位
        int tempBit = 1 << position; // position 左移 1(因为每一个 byte 下标从 0 开始)

        return (byteBits[index] | tempBit) != 0 ? 1 : 0; // 把 0 改成 1
    }

    public boolean getStatus(int offset) {
        int index = offset / 8; // 找到在哪个 byte 位
        int position = offset % 8; // 找到在 byte 的第几位
        int tempBit = 1 << position;
        return (byteBits[index] & tempBit) != 0; // 判断数字是否存在
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值