本篇文章給大家?guī)?lái)了關(guān)于Redis的相關(guān)知識(shí),其中主要介紹了bitmap問(wèn)題,Redis 為我們提供了位圖這一數(shù)據(jù)結(jié)構(gòu),位圖數(shù)據(jù)結(jié)構(gòu)其實(shí)并不是一個(gè)全新的玩意,我們可以簡(jiǎn)單的認(rèn)為就是個(gè)數(shù)組,只是里面的內(nèi)容只能為0或1而已,希望對(duì)大家有幫助。
推薦學(xué)習(xí):Redis視頻教程
1.位圖簡(jiǎn)介
如果我們需要記錄某一用戶(hù)在一年中每天是否有登錄我們的系統(tǒng)這一需求該如何完成呢?如果使用KV存儲(chǔ),每個(gè)用戶(hù)需要記錄365個(gè),當(dāng)用戶(hù)量上億時(shí),這所需要的存儲(chǔ)空間是驚人的。
Redis 為我們提供了位圖這一數(shù)據(jù)結(jié)構(gòu),每個(gè)用戶(hù)每天的登錄記錄只占據(jù)一位,365天就是365位,僅僅需要46字節(jié)就可存儲(chǔ),極大地節(jié)約了存儲(chǔ)空間。
位圖數(shù)據(jù)結(jié)構(gòu)其實(shí)并不是一個(gè)全新的玩意,我們可以簡(jiǎn)單的認(rèn)為就是個(gè)數(shù)組,只是里面的內(nèi)容只能為0或1而已(二進(jìn)制位數(shù)組)。
2.命令實(shí)戰(zhàn)
Redis提供了SETBIT
、GETBIT
、BITCOUNT
、BITOP
四個(gè)常用命令用于處理二進(jìn)制位數(shù)組。
SETBIT
:為位數(shù)組指定偏移量上的二進(jìn)制位設(shè)置值,偏移量從0開(kāi)始計(jì)數(shù),二進(jìn)制位的值只能為0或1。返回原位置值。GETBIT
:獲取指定偏移量上二進(jìn)制位的值。BITCOUNT
:統(tǒng)計(jì)位數(shù)組中值為1的二進(jìn)制位數(shù)量。BITOP
:對(duì)多個(gè)位數(shù)組進(jìn)行按位與、或、異或運(yùn)算。
127.0.0.1:6379> SETBIT first 0 1 # 0000 0001 (integer) 0 127.0.0.1:6379> SETBIT first 3 1 # 0000 1001 (integer) 0 127.0.0.1:6379> SETBIT first 0 0 # 0000 1000 (integer) 1 127.0.0.1:6379> GETBIT first 0 (integer) 0 127.0.0.1:6379> GETBIT first 3 (integer) 1 127.0.0.1:6379> BITCOUNT first # 0000 1000 (integer) 1 127.0.0.1:6379> SETBIT first 0 1 # 0000 1001 (integer) 0 127.0.0.1:6379> BITCOUNT first # 0000 1001 (integer) 2 127.0.0.1:6379> SETBIT first 1 1 # 0000 1011 (integer) 0 127.0.0.1:6379> BITCOUNT first # 0000 1011 (integer) 3 127.0.0.1:6379> SETBIT x 3 1 (integer) 0 127.0.0.1:6379> SETBIT x 1 1 (integer) 0 127.0.0.1:6379> SETBIT x 0 1 # 0000 1011 (integer) 0 127.0.0.1:6379> SETBIT y 2 1 (integer) 0 127.0.0.1:6379> SETBIT y 1 1 # 0000 0110 (integer) 0 127.0.0.1:6379> SETBIT z 2 1 (integer) 0 127.0.0.1:6379> SETBIT z 0 1 # 0000 0101 (integer) 0 127.0.0.1:6379> BITOP AND andRes x y z #0000 0000 (integer) 1 127.0.0.1:6379> BITOP OR orRes x y z #0000 1111 (integer) 1 127.0.0.1:6379> BITOP XOR x y z #0000 1000 (integer) 1 # 對(duì)給定的位數(shù)組進(jìn)行按位取反 127.0.0.1:6379> SETBIT value 0 1 (integer) 0 127.0.0.1:6379> SETBIT value 3 1 #0000 1001 (integer) 0 127.0.0.1:6379> BITOP NOT notValue value #1111 0110 (integer) 1
3.BitMap源碼分析
3.1 數(shù)據(jù)結(jié)構(gòu)
如下展示了一個(gè)用 SDS 表示的一字節(jié)(8位)長(zhǎng)的位圖:
擴(kuò)展:Redis 中的每個(gè)對(duì)象都是有一個(gè) redisObject 結(jié)構(gòu)表示的。
typedef struct redisObject { // 類(lèi)型 unsigned type:4; // 編碼 unsigned encoding:4; unsigned lru:REDIS_LRU_BITS; /* lru time (relative to server.lruclock) */ // 引用計(jì)數(shù) int refcount; // 執(zhí)行底層實(shí)現(xiàn)的數(shù)據(jù)結(jié)構(gòu)的指針 void *ptr; } robj;
type
的值為REDIS_STRING
表示這是一個(gè)字符串對(duì)象sdshdr.len
的值為1表示這個(gè)SDS保存了一個(gè)1字節(jié)大小的位數(shù)組- buf數(shù)組中的
buf[0]
實(shí)際保存了位數(shù)組 - buf數(shù)組中的
buf[1]
為自動(dòng)追加的