網(wǎng)站首頁 編程語言 正文
簡(jiǎn)介
本文基于Spring Boot 2.6.6、redisson 3.16.0簡(jiǎn)單分析Redisson布隆過濾器的使用。
布隆過濾器是一個(gè)非常長的二進(jìn)制向量和一系列隨機(jī)哈希函數(shù)的組合,可用于檢索一個(gè)元素是否存在;
使用場(chǎng)景如下:
- 解決Redis緩存穿透問題;
- 郵件過濾;
使用
- 建立一個(gè)二進(jìn)制向量,所有位設(shè)置0;
- 選擇K個(gè)散列函數(shù),用于對(duì)元素進(jìn)行K次散列,計(jì)算向量的位下標(biāo);
- 添加元素:將K個(gè)散列函數(shù)作用于該元素,生成K個(gè)值作為位下標(biāo),將向量的對(duì)應(yīng)位設(shè)置為1;
- 檢索元素:將K個(gè)散列函數(shù)作用于該元素,生成K個(gè)值作為位下標(biāo),若向量的對(duì)應(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>
測(cè)試代碼
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); ? ? ? ? // 測(cè)試檢索效果 ? ? ? ? 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); ? ? } }
簡(jiǎn)析
初始化
布隆過濾器的初始化方法tryInit有兩個(gè)參數(shù):
- expectedInsertions:預(yù)期的插入元素?cái)?shù)量;
- falseProbability:預(yù)期的錯(cuò)誤率;
布隆過濾器可以明確元素不存在,但對(duì)于元素存在的判斷是存在錯(cuò)誤率的;所以初始化時(shí)指定的這兩個(gè)參數(shù)會(huì)決定布隆過濾器的向量長度和散列函數(shù)的個(gè)數(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ù)元素個(gè)數(shù)和錯(cuò)誤率計(jì)算得到向量長度 ? ? 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ù)元素個(gè)數(shù)和向量長度計(jì)算得到散列函數(shù)的個(gè)數(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í),先使用一系列散列函數(shù)根據(jù)元素得到K個(gè)位下標(biāo),然后將向量中位下標(biāo)對(duì)應(yīng)的位設(shè)置為1;
RedissonBloomFilter.add方法代碼如下:
public boolean add(T object) { ? ? // 根據(jù)帶插入元素得到兩個(gè)long類型散列值 ? ? long[] hashes = hash(object); ? ? while (true) { ? ? ? ? if (size == 0) { ? ? ? ? ? ? readConfig(); ? ? ? ? } ? ? ? ? int hashIterations = this.hashIterations; ? ? ? ? long size = this.size; ? ? ? ? // 得到位下標(biāo)數(shù)組 ? ? ? ? // 以兩個(gè)散列值根據(jù)指定策略生成hashIterations個(gè)散列值,從而得到位下標(biāo) ? ? ? ? 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++) { ? ? ? ? ? ? // 將位下標(biāo)對(duì)應(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ù)的實(shí)現(xiàn)方式 ? ? ? ? if (i % 2 == 0) { ? ? ? ? ? ? // 新散列值 ? ? ? ? ? ? hash += hash2; ? ? ? ? } else { ? ? ? ? ? ? // 新散列值 ? ? ? ? ? ? hash += hash1; ? ? ? ? } ? ? } ? ? return indexes; }
hash(long hash1, long hash2, int iterations, long size)
方法中,利用根據(jù)元素得到的兩個(gè)散列值,生成一系列散列函數(shù),然后得到位下標(biāo)數(shù)組;
檢索元素
檢索布隆過濾器中是否存在指定元素時(shí),先使用一系列散列函數(shù)根據(jù)元素得到K個(gè)位下標(biāo),然后判斷向量中位下標(biāo)對(duì)應(yīng)的位是否為1,若存在一個(gè)不為1,則該元素不存在;否則認(rèn)為存在;
RedissonBloomFilter.contains方法代碼如下:
public boolean contains(T object) { ? ? // 根據(jù)帶插入元素得到兩個(gè)long類型散列值 ? ? long[] hashes = hash(object); ? ? while (true) { ? ? ? ? if (size == 0) { ? ? ? ? ? ? readConfig(); ? ? ? ? } ? ? ? ? int hashIterations = this.hashIterations; ? ? ? ? long size = this.size; ? ? ? ? // 得到位下標(biāo)數(shù)組 ? ? ? ? // 以兩個(gè)散列值根據(jù)指定策略生成hashIterations個(gè)散列值,從而得到位下標(biāo) ? ? ? ? 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++) { ? ? ? ? ? ? // 獲取位下標(biāo)對(duì)應(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的位,則認(rèn)為元素不存在 ? ? ? ? ? ? ? ? ? ? return false; ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? ? ? // 都為1,則認(rèn)為元素存在 ? ? ? ? ? ? return true; ? ? ? ? } catch (RedisException e) { ? ? ? ? ? ? if (e.getMessage() == null || !e.getMessage().contains("Bloom filter config has been changed")) { ? ? ? ? ? ? ? ? throw e; ? ? ? ? ? ? } ? ? ? ? } ? ? } }
原文鏈接:https://blog.csdn.net/xing_hung/article/details/124775160
相關(guān)推薦
- 2022-07-06 python數(shù)據(jù)分析之DateFrame數(shù)據(jù)排序和排名方式_python
- 2022-09-04 Python基礎(chǔ)之字典的詳細(xì)使用教程_python
- 2022-07-24 Python使用apscheduler模塊設(shè)置定時(shí)任務(wù)的實(shí)現(xiàn)_python
- 2022-10-20 Android?Flutter實(shí)現(xiàn)自定義下拉刷新組件_Android
- 2022-07-02 Python使用?TCP協(xié)議實(shí)現(xiàn)智能聊天機(jī)器人功能_python
- 2022-12-19 Tensorflow加載與預(yù)處理數(shù)據(jù)詳解實(shí)現(xiàn)方法_python
- 2022-04-22 qiankun框架下使用el-select或者分頁報(bào)錯(cuò)Failed to execute ‘getC
- 2022-07-28 docker容器間進(jìn)行數(shù)據(jù)共享的三種實(shí)現(xiàn)方式_docker
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支