最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Redis中Redisson布隆過濾器的學(xué)習(xí)

 更新時間:2022年05月16日 09:20:42   作者:我家有貓已長成  
布隆過濾器是一個非常長的二進制向量和一系列隨機哈希函數(shù)的組合,可用于檢索一個元素是否存在,本文就詳細的介紹一下Redisson布隆過濾器,具有一定的參考價值,感興趣的可以了解一下

簡介

本文基于Spring Boot 2.6.6、redisson 3.16.0簡單分析Redisson布隆過濾器的使用。

布隆過濾器是一個非常長的二進制向量和一系列隨機哈希函數(shù)的組合,可用于檢索一個元素是否存在;

使用場景如下:

  • 解決Redis緩存穿透問題;
  • 郵件過濾;

使用

  • 建立一個二進制向量,所有位設(shè)置0;
  • 選擇K個散列函數(shù),用于對元素進行K次散列,計算向量的位下標;
  • 添加元素:將K個散列函數(shù)作用于該元素,生成K個值作為位下標,將向量的對應(yīng)位設(shè)置為1;
  • 檢索元素:將K個散列函數(shù)作用于該元素,生成K個值作為位下標,若向量的對應(yīng)位都是1,則說明該元素可能存在;否則,該元素肯定不存在;

Demo

依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <exclusions>
        <exclusion>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>
<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>3.16.0</version>
</dependency>

測試代碼

public class BloomFilterDemo {

? ? public static void main(String[] args) {
? ? ? ? Config config = new Config();
? ? ? ? config.useSingleServer().setAddress("redis://127.0.0.1:6379");
? ? ? ? RedissonClient redissonClient = Redisson.create(config);
? ? ? ? RBloomFilter<String> bloomFilter = redissonClient.getBloomFilter("bloom-filter");
? ? ? ? // 初始化布隆過濾器
? ? ? ? bloomFilter.tryInit(200, 0.01);

? ? ? ? List<String> elements = new ArrayList<>();
? ? ? ? for (int i = 0; i < 200; i++) {
? ? ? ? ? ? elements.add(UUID.randomUUID().toString());
? ? ? ? }

? ? ? ? // 向布隆過濾器中添加內(nèi)容
? ? ? ? init(bloomFilter, elements);
? ? ? ? // 測試檢索效果
? ? ? ? test(bloomFilter, elements);

? ? ? ? redissonClient.shutdown();
? ? }

? ? public static void init(RBloomFilter<String> bloomFilter, List<String> elements) {
? ? ? ? for (int i = 0; i < elements.size(); i++) {
? ? ? ? ? ? if (i % 2 == 0) {
? ? ? ? ? ? ? ? bloomFilter.add(elements.get(i));
? ? ? ? ? ? }
? ? ? ? }
? ? }

? ? public static void test(RBloomFilter<String> bloomFilter, List<String> elements) {
? ? ? ? int counter = 0;
? ? ? ? for (String element : elements) {
? ? ? ? ? ? if (bloomFilter.contains(element)) {
? ? ? ? ? ? ? ? counter++;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? System.out.println(counter);
? ? }
}

簡析

初始化

布隆過濾器的初始化方法tryInit有兩個參數(shù):

  • expectedInsertions:預(yù)期的插入元素數(shù)量;
  • falseProbability:預(yù)期的錯誤率;

布隆過濾器可以明確元素不存在,但對于元素存在的判斷是存在錯誤率的;所以初始化時指定的這兩個參數(shù)會決定布隆過濾器的向量長度和散列函數(shù)的個數(shù);
RedissonBloomFilter.tryInit方法代碼如下:

public boolean tryInit(long expectedInsertions, double falseProbability) {
? ? if (falseProbability > 1) {
? ? ? ? throw new IllegalArgumentException("Bloom filter false probability can't be greater than 1");
? ? }
? ? if (falseProbability < 0) {
? ? ? ? throw new IllegalArgumentException("Bloom filter false probability can't be negative");
? ? }

? ? // 根據(jù)元素個數(shù)和錯誤率計算得到向量長度
? ? size = optimalNumOfBits(expectedInsertions, falseProbability);
? ? if (size == 0) {
? ? ? ? throw new IllegalArgumentException("Bloom filter calculated size is " + size);
? ? }
? ? if (size > getMaxSize()) {
? ? ? ? throw new IllegalArgumentException("Bloom filter size can't be greater than " + getMaxSize() + ". But calculated size is " + size);
? ? }
? ? // 根據(jù)元素個數(shù)和向量長度計算得到散列函數(shù)的個數(shù)
? ? hashIterations = optimalNumOfHashFunctions(expectedInsertions, size);

? ? CommandBatchService executorService = new CommandBatchService(commandExecutor);
? ? executorService.evalReadAsync(configName, codec, RedisCommands.EVAL_VOID,
? ? ? ? ? ? "local size = redis.call('hget', KEYS[1], 'size');" +
? ? ? ? ? ? ? ? ? ? "local hashIterations = redis.call('hget', KEYS[1], 'hashIterations');" +
? ? ? ? ? ? ? ? ? ? "assert(size == false and hashIterations == false, 'Bloom filter config has been changed')",
? ? ? ? ? ? ? ? ? ? Arrays.<Object>asList(configName), size, hashIterations);
? ? executorService.writeAsync(configName, StringCodec.INSTANCE,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? new RedisCommand<Void>("HMSET", new VoidReplayConvertor()), configName,
? ? ? ? ? ? "size", size, "hashIterations", hashIterations,
? ? ? ? ? ? "expectedInsertions", expectedInsertions, "falseProbability", BigDecimal.valueOf(falseProbability).toPlainString());
? ? try {
? ? ? ? executorService.execute();
? ? } catch (RedisException e) {
? ? ? ? if (e.getMessage() == null || !e.getMessage().contains("Bloom filter config has been changed")) {
? ? ? ? ? ? throw e;
? ? ? ? }
? ? ? ? readConfig();
? ? ? ? return false;
? ? }

? ? return true;
}

private 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)));
}

private int optimalNumOfHashFunctions(long n, long m) {
? ? return Math.max(1, (int) Math.round((double) m / n * Math.log(2)));
}

添加元素

向布隆過濾器中添加元素時,先使用一系列散列函數(shù)根據(jù)元素得到K個位下標,然后將向量中位下標對應(yīng)的位設(shè)置為1;
RedissonBloomFilter.add方法代碼如下:

public boolean add(T object) {
? ? // 根據(jù)帶插入元素得到兩個long類型散列值
? ? long[] hashes = hash(object);

? ? while (true) {
? ? ? ? if (size == 0) {
? ? ? ? ? ? readConfig();
? ? ? ? }

? ? ? ? int hashIterations = this.hashIterations;
? ? ? ? long size = this.size;

? ? ? ? // 得到位下標數(shù)組
? ? ? ? // 以兩個散列值根據(jù)指定策略生成hashIterations個散列值,從而得到位下標
? ? ? ? long[] indexes = hash(hashes[0], hashes[1], hashIterations, size);

? ? ? ? CommandBatchService executorService = new CommandBatchService(commandExecutor);
? ? ? ? addConfigCheck(hashIterations, size, executorService);
? ? ? ? RBitSetAsync bs = createBitSet(executorService);
? ? ? ? for (int i = 0; i < indexes.length; i++) {
? ? ? ? ? ? // 將位下標對應(yīng)位設(shè)置1
? ? ? ? ? ? bs.setAsync(indexes[i]);
? ? ? ? }
? ? ? ? try {
? ? ? ? ? ? List<Boolean> result = (List<Boolean>) executorService.execute().getResponses();

? ? ? ? ? ? for (Boolean val : result.subList(1, result.size()-1)) {
? ? ? ? ? ? ? ? if (!val) {
? ? ? ? ? ? ? ? ? ? // 元素添加成功
? ? ? ? ? ? ? ? ? ? return true;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? // 元素已存在
? ? ? ? ? ? return false;
? ? ? ? } catch (RedisException e) {
? ? ? ? ? ? if (e.getMessage() == null || !e.getMessage().contains("Bloom filter config has been changed")) {
? ? ? ? ? ? ? ? throw e;
? ? ? ? ? ? }
? ? ? ? }
? ? }
}

private long[] hash(Object object) {
? ? ByteBuf state = encode(object);
? ? try {
? ? ? ? return Hash.hash128(state);
? ? } finally {
? ? ? ? state.release();
? ? }
}

private long[] hash(long hash1, long hash2, int iterations, long size) {
? ? long[] indexes = new long[iterations];
? ? long hash = hash1;
? ? for (int i = 0; i < iterations; i++) {
? ? ? ? indexes[i] = (hash & Long.MAX_VALUE) % size;
? ? ? ? // 散列函數(shù)的實現(xiàn)方式
? ? ? ? if (i % 2 == 0) {
? ? ? ? ? ? // 新散列值
? ? ? ? ? ? hash += hash2;
? ? ? ? } else {
? ? ? ? ? ? // 新散列值
? ? ? ? ? ? hash += hash1;
? ? ? ? }
? ? }
? ? return indexes;
}

hash(long hash1, long hash2, int iterations, long size)方法中,利用根據(jù)元素得到的兩個散列值,生成一系列散列函數(shù),然后得到位下標數(shù)組;

檢索元素

檢索布隆過濾器中是否存在指定元素時,先使用一系列散列函數(shù)根據(jù)元素得到K個位下標,然后判斷向量中位下標對應(yīng)的位是否為1,若存在一個不為1,則該元素不存在;否則認為存在;
RedissonBloomFilter.contains方法代碼如下:

public boolean contains(T object) {
? ? // 根據(jù)帶插入元素得到兩個long類型散列值
? ? long[] hashes = hash(object);

? ? while (true) {
? ? ? ? if (size == 0) {
? ? ? ? ? ? readConfig();
? ? ? ? }

? ? ? ? int hashIterations = this.hashIterations;
? ? ? ? long size = this.size;

? ? ? ? // 得到位下標數(shù)組
? ? ? ? // 以兩個散列值根據(jù)指定策略生成hashIterations個散列值,從而得到位下標
? ? ? ? long[] indexes = hash(hashes[0], hashes[1], hashIterations, size);

? ? ? ? CommandBatchService executorService = new CommandBatchService(commandExecutor);
? ? ? ? addConfigCheck(hashIterations, size, executorService);
? ? ? ? RBitSetAsync bs = createBitSet(executorService);
? ? ? ? for (int i = 0; i < indexes.length; i++) {
? ? ? ? ? ? // 獲取位下標對應(yīng)位的值
? ? ? ? ? ? bs.getAsync(indexes[i]);
? ? ? ? }
? ? ? ? try {
? ? ? ? ? ? List<Boolean> result = (List<Boolean>) executorService.execute().getResponses();

? ? ? ? ? ? for (Boolean val : result.subList(1, result.size()-1)) {
? ? ? ? ? ? ? ? if (!val) {
? ? ? ? ? ? ? ? ? ? // 若存在不為1的位,則認為元素不存在
? ? ? ? ? ? ? ? ? ? return false;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? // 都為1,則認為元素存在
? ? ? ? ? ? return true;
? ? ? ? } catch (RedisException e) {
? ? ? ? ? ? if (e.getMessage() == null || !e.getMessage().contains("Bloom filter config has been changed")) {
? ? ? ? ? ? ? ? throw e;
? ? ? ? ? ? }
? ? ? ? }
? ? }
}

到此這篇關(guān)于Redis中Redisson布隆過濾器的學(xué)習(xí)的文章就介紹到這了,更多相關(guān)Redis Redisson布隆過濾器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Redis GEO實現(xiàn)搜索附近用戶的項目實踐

    Redis GEO實現(xiàn)搜索附近用戶的項目實踐

    RedisGEO主要用于存儲地理位置信息,并對存儲的信息進行操作,本文主要介紹了Redis GEO實現(xiàn)搜索附近用戶的項目實踐,具有一定的參考價值,感興趣的可以了解一下
    2024-05-05
  • Redis服務(wù)之高可用組件sentinel詳解

    Redis服務(wù)之高可用組件sentinel詳解

    這篇文章主要介紹了Redis服務(wù)之高可用組件sentinel,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-08-08
  • redis?zrange?與?zrangebyscore的區(qū)別解析

    redis?zrange?與?zrangebyscore的區(qū)別解析

    這篇文章主要介紹了redis?zrange與zrangebyscore的區(qū)別,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-06-06
  • Redis進行緩存操作的實現(xiàn)

    Redis進行緩存操作的實現(xiàn)

    本文主要介紹了Redis進行緩存操作,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2025-03-03
  • Redisson 主從一致性問題詳解

    Redisson 主從一致性問題詳解

    這篇文章主要為大家介紹了Redisson 主從一致性問題詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-08-08
  • Redis GEO實現(xiàn)附近搜索功能

    Redis GEO實現(xiàn)附近搜索功能

    這篇文章主要介紹了Redis GEO實現(xiàn)附近搜索功能,本文通過實例代碼給大家介紹的非常詳細,需要的朋友可以參考下
    2024-12-12
  • Redisson實現(xiàn)Redis分布式鎖的幾種方式

    Redisson實現(xiàn)Redis分布式鎖的幾種方式

    本文在講解如何使用Redisson實現(xiàn)Redis普通分布式鎖,以及Redlock算法分布式鎖的幾種方式的同時,也附帶解答這些同學(xué)的一些疑問,感興趣的可以了解一下
    2021-08-08
  • redis如何清理緩存

    redis如何清理緩存

    本文主要介紹了redis如何清理緩存,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-01-01
  • 淺談Redis對于過期鍵的三種清除策略

    淺談Redis對于過期鍵的三種清除策略

    本文主要介紹了Redis對于過期鍵的三種清除策略,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • Redis高級玩法之利用SortedSet實現(xiàn)多維度排序的方法

    Redis高級玩法之利用SortedSet實現(xiàn)多維度排序的方法

    Redis的SortedSet是可以根據(jù)score進行排序的,以手機應(yīng)用商店的熱門榜單排序為例,根據(jù)下載量倒序排列。接下來通過本文給大家分享Redis高級玩法之利用SortedSet實現(xiàn)多維度排序的方法,一起看看吧
    2019-07-07

最新評論

云龙县| 黔西| 简阳市| 巫溪县| 昭觉县| 利辛县| 利津县| 阳西县| 沂南县| 永安市| 澎湖县| 积石山| 台东市| 海南省| 宝应县| 苏尼特左旗| 井研县| 龙游县| 忻州市| 梓潼县| 富锦市| 弋阳县| 固始县| 介休市| 瓮安县| 舞阳县| 库尔勒市| 丹凤县| 茂名市| 元氏县| 湘乡市| 桃园市| 涟源市| 精河县| 通许县| 大宁县| 铜陵市| 志丹县| 鸡西市| 南昌市| 南漳县|