站長資訊網(wǎng)
最全最豐富的資訊網(wǎng)站

一文搞懂redis的bitmap

本篇文章給大家?guī)砹岁P(guān)于Redis的相關(guān)知識,其中主要介紹了bitmap問題,Redis 為我們提供了位圖這一數(shù)據(jù)結(jié)構(gòu),位圖數(shù)據(jù)結(jié)構(gòu)其實并不是一個全新的玩意,我們可以簡單的認(rèn)為就是個數(shù)組,只是里面的內(nèi)容只能為0或1而已,希望對大家有幫助。

一文搞懂redis的bitmap

推薦學(xué)習(xí):Redis視頻教程

1.位圖簡介

如果我們需要記錄某一用戶在一年中每天是否有登錄我們的系統(tǒng)這一需求該如何完成呢?如果使用KV存儲,每個用戶需要記錄365個,當(dāng)用戶量上億時,這所需要的存儲空間是驚人的。

Redis 為我們提供了位圖這一數(shù)據(jù)結(jié)構(gòu),每個用戶每天的登錄記錄只占據(jù)一位,365天就是365位,僅僅需要46字節(jié)就可存儲,極大地節(jié)約了存儲空間。

一文搞懂redis的bitmap

位圖數(shù)據(jù)結(jié)構(gòu)其實并不是一個全新的玩意,我們可以簡單的認(rèn)為就是個數(shù)組,只是里面的內(nèi)容只能為0或1而已(二進(jìn)制位數(shù)組)。

2.命令實戰(zhàn)

Redis提供了SETBITGETBITBITCOUNT、BITOP四個常用命令用于處理二進(jìn)制位數(shù)組。

  • SETBIT:為位數(shù)組指定偏移量上的二進(jìn)制位設(shè)置值,偏移量從0開始計數(shù),二進(jìn)制位的值只能為0或1。返回原位置值。
  • GETBIT:獲取指定偏移量上二進(jìn)制位的值。
  • BITCOUNT:統(tǒng)計位數(shù)組中值為1的二進(jìn)制位數(shù)量。
  • BITOP:對多個位數(shù)組進(jì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  # 對給定的位數(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)

如下展示了一個用 SDS 表示的一字節(jié)(8位)長的位圖:

一文搞懂redis的bitmap

擴(kuò)展:Redis 中的每個對象都是有一個 redisObject 結(jié)構(gòu)表示的。

typedef struct redisObject { // 類型 unsigned type:4; // 編碼 unsigned encoding:4; unsigned lru:REDIS_LRU_BITS; /* lru time (relative to server.lruclock) */ // 引用計數(shù) int refcount; // 執(zhí)行底層實現(xiàn)的數(shù)據(jù)結(jié)構(gòu)的指針 void *ptr; } robj;