数据结构模型
现代计算机使用二进制(位)作为信息的基础单位,1个字节等于8位,例如:big 字符串是由3个字符组成,但是在计算机存储时将其用二进制表示,big 分别对应的ASCII 如下图:

- BitMap本身不是一种数据结构,实际上它就是字符串,但是它可以对字符串的位进行操作。
- BitMap 单独提供了一套命令,所以在Redis 中使用BitMap 和 使用字符串的方法不太相同,可以把BitMap 想象成一个以位为单位的数组,数组的每个单元只能存储0和1,数组的下标在BitMap 中叫做偏移量。
命令
本节将每个独立用户是否访问过网站存放在BitMap 中,将访问的用户记做1,没有访问的用户记做0,用偏移量作为用户的ID。
- 设置 值:set key offset value
设置键的第 offset 个位的值 (从0算起) ,假设现在由20个用户,userId= 2,6,12,16,20 的用户对网站进行了访问(用户Id 减 1 为 数组下标),那么当前BitMap 初始化结果如图:

具体操作过程如下: unique:users:20210602 代表 2021-06-02 这条独立访问的用户的BitMap。
offset = userId -1
127.0.0.1:6379> setbit unique:users:20210602 1 1
(integer) 0
127.0.0.1:6379> setbit unique:users:20210602 5 1
(integer) 0
127.0.0.1:6379> setbit unique:users:20210602 11 1
(integer) 0
127.0.0.1:6379> setbit unique:users:20210602 15 1
(integer) 0
127.0.0.1:6379> setbit unique:users:20210602 19 1
(integer) 0
127.0.0.1:6379>
如果此时有一个userId = 30的用户访问了网站,那么BitMap 结构变成图:

2 获取 值:getbit key offset
userId= 2,6,12,16,20 的用户对网站进行了访问(用户Id 减 1 为 数组下标)
127.0.0.1:6379> getbit unique:users:20210602 1
(integer) 1
127.0.0.1:6379> getbit unique:users:20210602 5
(integer) 1
127.0.0.1:6379> getbit unique:users:20210602 11
(integer) 1
127.0.0.1:6379> getbit unique:users:20210602 15
(integer) 1
127.0.0.1:6379> getbit unique:users:20210602 19
(integer) 1
127.0.0.1:6379>