Redis new data type-bitmaps

Bilibili video explanation: https://www.bilibili.com/video/BV1Rv41177Af?p=15

Introduction

Modern computers use binary (bit) as the basic unit of information. 1 byte is equal to 8 bits. For example, the string "abc" is composed of 3 bytes, but it is actually expressed in binary when stored in the computer, "abc" The corresponding ASCII codes are 97, 98, 99, and the corresponding binary codes are 01100001, 01100010, and 01100011, as shown in the figure below

Insert picture description here

Reasonable use of operation bits can effectively improve memory usage and development efficiency.

(1) Bitmaps本身不是一种数据类型, 实际上它就是字符串(key-value) , 但是它可以对字符串的位进行操作。
(2)Bitmaps单独提供了一套命令, 所以在Redis中使用Bitmaps和使用字符串的方法不太相同。 可以把Bitmaps想象成一个以位为单位的数组, 数组的每个单元只能存储0和1, 数组的下标在Bitmaps中叫做偏移量。
Insert picture description here

command

# 设置Bitmaps中某个偏移量的值(value值为0或1),偏移量从0开始
setbit <key> <offset> <value>

# 获取Bitmaps字节数组中某个偏移量的值
getbit <key> <offset>

# 统计字符串从start字节到end字节比特值为1的数量 (0 到 -1)表示0到最后
bitcount <key> [start end]

# bitop是一个复合操作, 它可以做多个Bitmaps的and(交集) 、 or(并集) 、 not(非) 、 xor(异或) 
# 操作并将结果保存在新的destkey中。
bitop and (or/not/xor) <destkey> [key…]

Bitmaps and set comparison

Assuming that the website has 100 million users and 50 million users who visit independently every day, if you use the collection type and Bitmaps to store the active users every day, you can get the table

Insert picture description here

obviously. In this case, using Bitmaps can save a lot of memory space, especially with The memory saved over time is still considerable

Insert picture description here
Insert picture description here