BloomFilter基于redis的實現(xiàn)

BloomFilter

BloomFilter是一種空間效率的概率型數(shù)據(jù)結(jié)構(gòu),由Burton Howard Bloom 1970年提出的钮莲。通常用來判斷一個元素是否在集合中免钻。具有極高的空間效率,但是會帶來假陽性(False positive)的錯誤崔拥。

False positive&&False negatives

由于BloomFiter犧牲了一定的準(zhǔn)確率換取空間效率极舔。所以帶來了False positive的問題。

False positive

BloomFilter在判斷一個元素在集合中的時候握童,會出現(xiàn)一定的錯誤率姆怪,這個錯誤率稱為False positive的。通吃杓ǎ縮寫為fpp.

False negatives

BloomFilter判斷一個元素不在集合中的時候的錯誤率稽揭。 BloomFilter判斷該元素不在集合中,則該元素一定不再集合中肥卡。故False negatives概率為0.

算法描述

BloomFilter使用長度為m bit的字節(jié)數(shù)組溪掀,使用k個hash函數(shù),
增加一個元素: 通過k次hash將元素映射到字節(jié)數(shù)組中k個位置中步鉴,并設(shè)置對應(yīng)位置的字節(jié)為1.
查詢元素是否存在: 將元素k次hash得到k個位置揪胃,如果對應(yīng)k個位置的bit是1則認為存在,反之則認為不存在氛琢。

bit數(shù)組大小估算

m=-\frac{n * lnfpp}{ln2^2}
k=\frac{m}{n} * ln2 = -\frac{n * lnfpp}{ln2^2}
其中m為bit數(shù)組大小喊递,fpp為預(yù)估的假陽性概率,n為預(yù)估插入值數(shù)量阳似,k為hash次數(shù)骚勘。具體公式推導(dǎo)可以參考wiki。
可以看見隨著插入數(shù)量的增多和假陽性概率降低(更高的準(zhǔn)確率)所需要的空間大小會增加。

以上介紹了BloomFilter的一些基本的概念俏讹,下面來看看BloomFilter的使用当宴。

BloomFilter Guava

Guava中實現(xiàn)了BloomFilter, 首先看一個簡單例子。

示例

    public void testGuavaBloomFilter() {
        BloomFilter<String> bloomFilter = BloomFilter.create((Funnel<String>) (from, into) -> {
            into.putString(from, Charsets.UTF_8);
        }, 100_0000, 0.000_0001);

        String testElement1 = "123";
        String testElement2 = "456";
        String testElement3 = "789";

        bloomFilter.put(testElement1);
        bloomFilter.put(testElement2);
        System.out.println(bloomFilter.mightContain(testElement1));
        System.out.println(bloomFilter.mightContain(testElement2));
        System.out.println(bloomFilter.mightContain(testElement3));

    }

通過BloomFiter類create方法創(chuàng)建了一個預(yù)計插入數(shù)為100w, fpp為0.0000001的BloomFilter. 調(diào)用BloomFiter#put插入元素泽疆,通過mightContain來判斷元素是否存在户矢。

內(nèi)部實現(xiàn)

上面介紹了BloomFilter的使用,下面來分析下BloomFilter的內(nèi)部實現(xiàn)殉疼。
Guava Bloomfilter 實現(xiàn)主要涉及到BloomFilter以及BloomFilterStrategies梯浪,我們首先看下BloomFilter的一些重要函數(shù)

1 create

BloomFilter調(diào)用create方法會傳入三個參數(shù)
1 funnel
2 expectedInsertions 預(yù)故插入的數(shù)量
3 fpp 假陽性的概率

  static <T> BloomFilter<T> create(
      Funnel<? super T> funnel, long expectedInsertions, double fpp, Strategy strategy) {
        long numBits = optimalNumOfBits(expectedInsertions, fpp);
    int numHashFunctions = optimalNumOfHashFunctions(expectedInsertions, numBits);
    try {
      return new BloomFilter<T>(new BitArray(numBits), numHashFunctions, funnel, strategy);
    } catch (IllegalArgumentException e) {
      throw new IllegalArgumentException("Could not create BloomFilter of " + numBits + " bits", e);
    }
  }

create會對傳入的參數(shù)進行校驗,然后調(diào)用optimalNumOfBits&&optimalNumOfHashFunctions 算出所需的bit數(shù)組的大小以及hash函數(shù)的個數(shù)株依。

  static long optimalNumOfBits(long n, double p) {
    if (p == 0) {
      p = Double.MIN_VALUE;
    }
    return (long) (-n * Math.log(p) / (Math.log(2) * Math.log(2)));
  }


  static int optimalNumOfHashFunctions(long n, long m) {
    // (m / n) * log(2), but avoid truncation due to division!
    return Math.max(1, (int) Math.round((double) m / n * Math.log(2)));
  }

optimalNumOfBits&&optimalNumOfHashFunctions方法實現(xiàn)BloomFilter bit數(shù)組大小以及hash函數(shù)的計算公式驱证。

put
  public boolean put(T object) {
    return strategy.put(object, funnel, numHashFunctions, bits);
  }

BloomFilter#put實現(xiàn)是直接調(diào)用BloomFilter.Strategy#put, BloomFilter.Strategy的實現(xiàn)是通過策略枚舉, 目前有兩個實現(xiàn)MURMUR128_MITZ_32,MURMUR128_MITZ_64.
但是create方法中默認只會使用到MURMUR128_MITZ_64. 所以我們主要看看MURMUR128_MITZ_64的實現(xiàn).

    //BloomFilterStrategies.MURMUR128_MITZ_64
    public <T> boolean put(
        T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits) {
      long bitSize = bits.bitSize();
      byte[] bytes = Hashing.murmur3_128().hashObject(object, funnel).getBytesInternal();
      long hash1 = lowerEight(bytes);
      long hash2 = upperEight(bytes);

      boolean bitsChanged = false;
      long combinedHash = hash1;
      for (int i = 0; i < numHashFunctions; i++) {
        // Make the combined hash positive and indexable
        bitsChanged |= bits.set((combinedHash & Long.MAX_VALUE) % bitSize);
        combinedHash += hash2;
      }
      return bitsChanged;

1 put方法使用128bit murmur3哈希算法對object進行hash得到128bit字節(jié)數(shù)組.
2 然后分別取低8位置創(chuàng)建hash1延窜,高8位創(chuàng)建hash2.
3 然后通過hash1+hash2累加來模擬實現(xiàn)k次哈希恋腕, 并取摸設(shè)置相應(yīng)的bit位為1.

mightContain
  public boolean put(T object) {
    return strategy.put(object, funnel, numHashFunctions, bits);
  }

BloomFilter#mightContain的實現(xiàn)也是直接調(diào)用BloomFilter.Strategy#mightContain

    //BloomFilterStrategies.MURMUR128_MITZ_64
    public <T> boolean mightContain(
        T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits) {
      long bitSize = bits.bitSize();
      byte[] bytes = Hashing.murmur3_128().hashObject(object, funnel).getBytesInternal();
      long hash1 = lowerEight(bytes);
      long hash2 = upperEight(bytes);

      long combinedHash = hash1;
      for (int i = 0; i < numHashFunctions; i++) {
        // Make the combined hash positive and indexable
        if (!bits.get((combinedHash & Long.MAX_VALUE) % bitSize)) {
          return false;
        }
        combinedHash += hash2;
      }
      return true;
    }

BloomFilterStrategies#mightContain和put方法類似通過hash1和hash2相加模擬k次哈希, 循環(huán)中任何一次對應(yīng)bit為0則認為不存在,否則認為是存在的逆瑞。
這個方法名取的很不錯荠藤,mightContain返回true只能表示對應(yīng)元素可能存在集合中,因為存在fpp可能性获高。

BloomFilter基于redis實現(xiàn)

上一部分已經(jīng)分析了guava中Bloomfilter實現(xiàn)哈肖,guava版實現(xiàn)主要問題在于無法支持集群環(huán)境. 為了支持集群環(huán)境主要考慮通過redis setbit來實現(xiàn)BloomFilter

SETBIT: Sets or clears the bit at offset in the string value stored at key.The bit is either set or cleared depending on value, which can be either 0 or 1. When key does not exist, a new string value is created. The string is grown to make sure it can hold a bit at offset. The offset argument is required to be greater than or equal to 0, and smaller than 2^32 (this limits bitmaps to 512MB). When the string at key is grown, added bits are set to 0

setbit在redis中value其實是以string類型存儲。支持自增長最大能支持增長到2^32,也就是512MB念秧。

實現(xiàn)

Guava中最后通過操作BloomFilterStrategies.BitArray,故這里改造主要考慮替換BitArray實現(xiàn)淤井。這里主要貼出一些主要的代碼。

#me.ttting.common.hash.BitArray
public interface BitArray {
    void setBitSize(long bitSize);

    boolean set(long index);

    boolean get(long index);

    long bitSize();
}

定義一個BitArray接口,改造BloomFilterStrategies面向BitArray接口編程摊趾。

    @Override
    public void setBitSize(long bitSize) {
        if (bitSize > MAX_REDIS_BIT_SIZE)
            throw new IllegalArgumentException("Invalid redis bit size, must small than 2 to the 32");

        this.bitSize = bitSize;
    }

    @Override
    public boolean set(long index) {
        boolean result;
        result = (Boolean) execute(jedis -> {
            Boolean setbit = jedis.setbit(key, index, true);
            return !setbit;
        });
        return result;
    }

    @Override
    public boolean get(long index) {
        boolean result;
        result = (Boolean) execute(jedis -> jedis.getbit(key, index));
        return result;
    }

基于jedis實現(xiàn)一個基于redis版本的Bloomfilter. 后續(xù)通過增加BitArray的實現(xiàn)可以替換成任意實現(xiàn)币狠。

示例

    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool("localhost", 6379);
        JedisBitArray jedisBitArray = new JedisBitArray(jedisPool, "test-1");
        BloomFilter<String> bloomFilter = BloomFilter.create((Funnel<String>) (from, into) 
        ->into.putString(from, Charsets.UTF_8), 1_0000_0000, 0.0000001, BloomFilterStrategies.MURMUR128_MITZ_32, jedisBitArray);

        bloomFilter.put("111");
        bloomFilter.put("222");
        System.out.println(bloomFilter.mightContain("111"));
        System.out.println(bloomFilter.mightContain("222"));
        System.out.println(bloomFilter.mightContain("333"));

    }

具體的使用和實現(xiàn)可見https://github.com/ttting/redis-bloomfilter

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市砾层,隨后出現(xiàn)的幾起案子漩绵,更是在濱河造成了極大的恐慌,老刑警劉巖肛炮,帶你破解...
    沈念sama閱讀 219,490評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件止吐,死亡現(xiàn)場離奇詭異,居然都是意外死亡侨糟,警方通過查閱死者的電腦和手機碍扔,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來秕重,“玉大人不同,你說我怎么就攤上這事”” “怎么了套鹅?”我有些...
    開封第一講書人閱讀 165,830評論 0 356
  • 文/不壞的土叔 我叫張陵站蝠,是天一觀的道長。 經(jīng)常有香客問我卓鹿,道長菱魔,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,957評論 1 295
  • 正文 為了忘掉前任吟孙,我火速辦了婚禮澜倦,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘杰妓。我一直安慰自己藻治,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,974評論 6 393
  • 文/花漫 我一把揭開白布巷挥。 她就那樣靜靜地躺著桩卵,像睡著了一般。 火紅的嫁衣襯著肌膚如雪倍宾。 梳的紋絲不亂的頭發(fā)上雏节,一...
    開封第一講書人閱讀 51,754評論 1 307
  • 那天,我揣著相機與錄音高职,去河邊找鬼钩乍。 笑死,一個胖子當(dāng)著我的面吹牛怔锌,可吹牛的內(nèi)容都是我干的寥粹。 我是一名探鬼主播,決...
    沈念sama閱讀 40,464評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼埃元,長吁一口氣:“原來是場噩夢啊……” “哼涝涤!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起亚情,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤妄痪,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后楞件,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體衫生,經(jīng)...
    沈念sama閱讀 45,847評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,995評論 3 338
  • 正文 我和宋清朗相戀三年土浸,在試婚紗的時候發(fā)現(xiàn)自己被綠了罪针。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,137評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡黄伊,死狀恐怖泪酱,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤墓阀,帶...
    沈念sama閱讀 35,819評論 5 346
  • 正文 年R本政府宣布毡惜,位于F島的核電站,受9級特大地震影響斯撮,放射性物質(zhì)發(fā)生泄漏经伙。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,482評論 3 331
  • 文/蒙蒙 一勿锅、第九天 我趴在偏房一處隱蔽的房頂上張望帕膜。 院中可真熱鬧,春花似錦溢十、人聲如沸垮刹。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽荒典。三九已至,卻和暖如春乌庶,著一層夾襖步出監(jiān)牢的瞬間种蝶,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評論 1 272
  • 我被黑心中介騙來泰國打工瞒大, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人搪桂。 一個月前我還...
    沈念sama閱讀 48,409評論 3 373
  • 正文 我出身青樓透敌,卻偏偏與公主長得像,于是被迫代替她去往敵國和親踢械。 傳聞我的和親對象是個殘疾皇子酗电,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,086評論 2 355

推薦閱讀更多精彩內(nèi)容