统计 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; // 判断数字是否存在
}
}