《Redis开发与运维读书笔记》
数据结构模型
- Bitmaps本身不是一种数据结构,实际上它就是字符串但是它可以对字符串的位进行操作。
- 可以将Bitmaps想象成一个一个只能保存0或1的的以位为单位的数组,数组的下标在Bitmaps中叫做偏移量。
常用命令:
-
设置值
setbit key offset value
其中偏移量offset
从0开始。第一次初始化Bitmaps如果偏移量非常大,那么整个初始化过程会非常慢,可能造成Reids的阻塞
-
获取值
getbit key offset
-
获取Bitmaps指定范围值为1的个数
bitcount [start] [end]
-
Bitmaps间的运算
bitop [and | or | not | xor] destkey key [keys...]
and交集、or并集、not非、xor异或
-
计算Bitmaps中第一个值为targetBit的偏移量
bitpos key targetBit [start] [end]
Bitmaps分析
当数据量大是Bitmaps能节省很多的空间,但是如果数据量比较小而数据的偏移量比较大时Bitmaps反而会比较浪费空间。
应用场景
每个独立用户对网站的访问记录
- 将每个独立用户是否访问过网站保存到Bitmaps中,将方位的用户标识为1,没有访问过得用户标识为0;
setbit unique:users:2018-09-19 ${userId} 1
其中${userId}
为偏移量 - 获取id为8的用户是在在***2018-09-19***访问过网站
getbit unique:users:2018-09-19 8
- 获取 2018-09-19 这一天独立访问的用户数
bitcount unique:users:2018-09-19
- 获取 2018-09-19 和 2018-09-20 这两天都访问过网站的用户
bitop and unique:users:2018-09-19-20 unique:users:2018-09-19 unique:users:2018-09-20
- 计算 2018-09-19 访问过网站的最小用户id
bitops unique:users:2018-09-19-20 1