Redis從入門到放棄系列(四) Set

Redis從入門到放棄系列(四) Set

本文例子基於:5.0.4 Set是Redis中一種比較常見的數據結構,當存儲的member爲十進制64位有符號整數範圍內的整數的字符串的時候其實現爲intset,其餘爲hashtablejava

Redis從入門到放棄系列(三) Listpython

首先讓咱們來看一下該如何在redis裏面使用Set類型c++

//設置key的集合中的值爲member
sadd key member [member ...]

代碼示例:

> sadd books java python c
(integer) 3
//當咱們重複添加相同的數據的時候,redis返回爲0
> sadd books java python c
(integer) 0
----------------------------------
//返回books集合的全部元素
>smembers books 
1) "c"
2) "python"
3) "java"
----------------------------------
//判斷某個元素是否在集合裏面
>sismember books c
(integer) 1
>sismember books 99
(integer) 0
----------------------------------
//兩個集合的交集
> sadd new_books java c++ R
(integer) 3
> SINTER books new_books
1) "java"
----------------------------------
//兩個集合的並集
> SUNION books new_books
1) "java"
2) "python"
3) "c"
4) "c++"
5) "R"
//兩個集合的差集
> SMEMBERS books
1) "c"
2) "python"
3) "java"
> SMEMBERS new_books
1) "R"
2) "c++"
3) "java"
>  SDIFF books new_books
1) "python"
2) "c"
>  SDIFF new_books books
1) "R"
2) "c++"

至此,redis set的用法先告一段落.redis


源碼解析

本文開頭的時候講set實現分爲intset跟hashtable,hashtable這塊講解的話能夠去回頭看一下Redis從入門到放棄系列(二) Hash 本節重點來說一下intset~當存儲元素爲整數的時候,redis爲了節省空間,採用了intset這種數據結構來作存儲,咱們知道set結構存儲字符串的時候都是無序的,可當採用intset來存儲的整數的時候, set是有序的,內部採用了二分法方便快速查詢 讓咱們先來看一下intset內部結構數據結構

typedef struct intset {
    uint32_t encoding;
    uint32_t length;
    int8_t contents[];
} intset;

咱們發現intset裏面實際上是由一個變量類型,一個長度表示的,也就是說要計算當前intset佔據的字節:encoding * length; redis在使用intset的時候,首先會判斷當前插入的value的大小,而後返回不一樣字節的類型app

/* Note that these encodings are ordered, so:
 * INTSET_ENC_INT16 < INTSET_ENC_INT32 < INTSET_ENC_INT64. */
#define INTSET_ENC_INT16 (sizeof(int16_t))
#define INTSET_ENC_INT32 (sizeof(int32_t))
#define INTSET_ENC_INT64 (sizeof(int64_t))

/* Return the required encoding for the provided value. */
static uint8_t _intsetValueEncoding(int64_t v) {
    if (v < INT32_MIN || v > INT32_MAX)
        return INTSET_ENC_INT64;
    else if (v < INT16_MIN || v > INT16_MAX)
        return INTSET_ENC_INT32;
    else
        return INTSET_ENC_INT16;
}

當每次插入的value的值大於當前類型的話,redis會將intset升級爲更大的編碼ide

/* Upgrades the intset to a larger encoding and inserts the given integer. */
static intset *intsetUpgradeAndAdd(intset *is, int64_t value) {
    uint8_t curenc = intrev32ifbe(is->encoding);
    uint8_t newenc = _intsetValueEncoding(value);
    int length = intrev32ifbe(is->length);
    int prepend = value < 0 ? 1 : 0;

    /* First set new encoding and resize */
    is->encoding = intrev32ifbe(newenc);
    is = intsetResize(is,intrev32ifbe(is->length)+1);

    /* Upgrade back-to-front so we don't overwrite values.
     * Note that the "prepend" variable is used to make sure we have an empty
     * space at either the beginning or the end of the intset. */
    while(length--)
        _intsetSet(is,length+prepend,_intsetGetEncoded(is,length,curenc));

    /* Set the value at the beginning or the end. */
    if (prepend)
        _intsetSet(is,0,value);
    else
        _intsetSet(is,intrev32ifbe(is->length),value);
    is->length = intrev32ifbe(intrev32ifbe(is->length)+1);
    return is;
}

前面咱們說過,intset是一個有序的,而後查找的時候採用了二分法來查找元素,那麼其內部是如何實現的呢?ui

/* Search for the position of "value". Return 1 when the value was found and
 * sets "pos" to the position of the value within the intset. Return 0 when
 * the value is not present in the intset and sets "pos" to the position
 * where "value" can be inserted. */
static uint8_t intsetSearch(intset *is, int64_t value, uint32_t *pos) {
    int min = 0, max = intrev32ifbe(is->length)-1, mid = -1;
    int64_t cur = -1;

    /* The value can never be found when the set is empty */
    if (intrev32ifbe(is->length) == 0) {
        if (pos) *pos = 0;
        return 0;
    } else {
        /* Check for the case where we know we cannot find the value,
         * but do know the insert position. */
        if (value > _intsetGet(is,max)) {
            if (pos) *pos = intrev32ifbe(is->length);
            return 0;
        } else if (value < _intsetGet(is,0)) {
            if (pos) *pos = 0;
            return 0;
        }
    }

    while(max >= min) {
        mid = ((unsigned int)min + (unsigned int)max) >> 1;
        cur = _intsetGet(is,mid);
        if (value > cur) {
            min = mid+1;
        } else if (value < cur) {
            max = mid-1;
        } else {
            break;
        }
    }

    if (value == cur) {
        if (pos) *pos = mid;
        return 1;
    } else {
        if (pos) *pos = min;
        return 0;
    }
}
/* Insert an integer in the intset */
intset *intsetAdd(intset *is, int64_t value, uint8_t *success) {
    uint8_t valenc = _intsetValueEncoding(value);
    uint32_t pos;
    if (success) *success = 1;

    /* Upgrade encoding if necessary. If we need to upgrade, we know that
     * this value should be either appended (if > 0) or prepended (if < 0),
     * because it lies outside the range of existing values. */
    if (valenc > intrev32ifbe(is->encoding)) {
        /* This always succeeds, so we don't need to curry *success. */
        return intsetUpgradeAndAdd(is,value);
    } else {
        /* Abort if the value is already present in the set.
         * This call will populate "pos" with the right position to insert
         * the value when it cannot be found. */
        if (intsetSearch(is,value,&pos)) {
            if (success) *success = 0;
            return is;
        }

        is = intsetResize(is,intrev32ifbe(is->length)+1);
        if (pos < intrev32ifbe(is->length)) intsetMoveTail(is,pos,pos+1);
    }

    _intsetSet(is,pos,value);
    is->length = intrev32ifbe(intrev32ifbe(is->length)+1);
    return is;
}

重點在while操做那一段~咱們能夠看到,其查找採用了二分法,那麼如何讓其有序呢?this

if (intsetSearch(is,value,&pos)) {
    if (success) *success = 0;
    return is;
}

看到這一段了吧?判斷查找的時候,將pos的位置查找了出來,給下面_intsetSet操做作前奏~編碼

應用場景

1.去重~ 2.查看兩我的的共同愛好

寫在最後

祝你們520快樂~

相關文章
相關標籤/搜索