服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - Redis - Redis中Bloom filter布隆过滤器的学习

Redis中Bloom filter布隆过滤器的学习

2022-12-15 16:49枫灵小宇 Redis

布隆过滤器是一个非常长的二进制向量和一系列随机哈希函数的组合,可用于检索一个元素是否存在,本文就详细的介绍一下Bloom filter布隆过滤器,具有一定的参考价值,感兴趣的可以了解一下

1.概念

​ 布隆过滤器是一个高空间利用率的概率性数据结构,主要目的是节省内存空间以及判断一个元素是否存在于一个集合中(存在误判的情况),可以理解为一个不怎么精确的 set 结构,当你使用它的 contains 方法判断某个对象是否存在时,它可能会误判。但是布隆过滤器也不是特别不精确,只要参数设置的合理,它的精确度可以控制的相对足够精确,只会有小小的误判概率(控制参数:error_rate-误判率 initial_size-初始容量)

​ error_rate越小,越精确,需要的空间越大

​ initial_size越大,越精确,当实际数量超出这个数值时,误判率会上升

布隆过滤器可以判断某个数据一定不存在,但是无法判断一定存在

2.guava实现

2.1.依赖

?
1
2
3
4
5
6
<!--guava实现布隆过滤器-->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>19.0</version>
</dependency>

2.2.初始化布隆过滤器

?
1
2
3
4
5
6
//初始化布隆过滤器,放入到spring容器里面
@Bean
public MyBloomFilter<String> initBloomFilterHelper() {
    return new MyBloomFilter<>((Funnel<String>) (from, into) -> into.putString(from, Charsets.UTF_8).putString(from, Charsets.UTF_8)
                               , 1000000, 0.01);
}

2.3.布隆过滤器

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.qin.redis.bloomfilter;
import com.google.common.base.Preconditions;
import com.google.common.hash.Funnel;
import com.google.common.hash.Hashing;
/**
 * @version: V1.0.0
 * @className: MyBloomFilter
 */
public class MyBloomFilter<T> {
    private int numHashFunctions;
    private int bitSize;
    private Funnel<T> funnel;
    public MyBloomFilter(Funnel<T> funnel, int expectedInsertions, double fpp) {
        Preconditions.checkArgument(funnel != null, "funnel不能为空");
        this.funnel = funnel;
        // 计算bit数组长度
        bitSize = optimalNumOfBits(expectedInsertions, fpp);
        // 计算hash方法执行次数
        numHashFunctions = optimalNumOfHashFunctions(expectedInsertions, bitSize);
    }
    public int[] murmurHashOffset(T value) {
        int[] offset = new int[numHashFunctions];
        long hash64 = Hashing.murmur3_128().hashObject(value, funnel).asLong();
        int hash1 = (int) hash64;
        int hash2 = (int) (hash64 >>> 32);
        for (int i = 1; i <= numHashFunctions; i++) {
            int nextHash = hash1 + i * hash2;
            if (nextHash < 0) {
                nextHash = ~nextHash;
            }
            offset[i - 1] = nextHash % bitSize;
        }
        return offset;
    }
    /**
     * 计算bit数组长度
     */
    private int optimalNumOfBits(long n, double p) {
        if (p == 0) {
            // 设定最小期望长度
            p = Double.MIN_VALUE;
        }
        int sizeOfBitArray = (int) (-n * Math.log(p) / (Math.log(2) * Math.log(2)));
        return sizeOfBitArray;
    }
    /**
     * 计算hash方法执行次数
     */
    private static int optimalNumOfHashFunctions(long n, long m) {
        int countOfHash = Math.max(1, (int) Math.round((double) m / n * Math.log(2)));
        return countOfHash;
    }
    public static void main(String[] args) {
        System.out.println(optimalNumOfHashFunctions(1000000000L, 123450000L));
    }
}

2.4.添加元素或者判断是否存在

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.qin.redis.bloomfilter.service;
import com.google.common.base.Preconditions;
import com.hikvison.aksk.redis.bloomfilter.MyBloomFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
/**
 * @version: V1.0.0
 * @className: RedisBloomFilterService
 */
@Service
public class RedisBloomFilterService {
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 根据给定的布隆过滤器添加值
     */
    public <T> void addByBloomFilter(MyBloomFilter<T> bloomFilterHelper, String key, T value) {
        Preconditions.checkArgument(bloomFilterHelper != null, "myBloomFilter不能为空");
        int[] offset = bloomFilterHelper.murmurHashOffset(value);
        for (int i : offset) {
            System.out.println("key : " + key + " " + "value : " + i);
            redisTemplate.opsForValue().setBit(key, i, true);
        }
    }
    /**
     * 根据给定的布隆过滤器判断值是否存在
     */
    public <T> boolean includeByBloomFilter(MyBloomFilter<T> bloomFilterHelper, String key, T value) {
        Preconditions.checkArgument(bloomFilterHelper != null, "myBloomFilter不能为空");
        int[] offset = bloomFilterHelper.murmurHashOffset(value);
        for (int i : offset) {
            System.out.println("key : " + key + " " + "value : " + i);
            if (!redisTemplate.opsForValue().getBit(key, i)) {
                return false;
            }
        }
        return true;
    }
}

3.Redisson实现

3.1.依赖

?
1
2
3
4
5
<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>2.7.0</version>
</dependency>

3.2.注入或测试

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//单机模式:可以设置集群、哨兵模式
   @Bean
   public Redisson redisson() {
       Config config = new Config();
       config.useSingleServer().setAddress("redis://127.0.0.1:6379");
       RedissonClient redissonClient = Redisson.create(config);
       //初始化过滤器
       RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter("testBloomFilter");
       bloomFilter.tryInit(1000000L,0.05);
       //插入元素
       bloomFilter.add("zhangsan");
       bloomFilter.add("lisi");
       //判断元素是否存在
       boolean flag = bloomFilter.contains("lisi");
       return (Redisson) redissonClient;
   }

到此这篇关于Redis中Bloom filter布隆过滤器的学习的文章就介绍到这了,更多相关Redis布隆过滤器内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_42513284/article/details/112252123

延伸 · 阅读

精彩推荐
  • RedisRedis安装及基本数据类型

    Redis安装及基本数据类型

    这篇文章主要介绍了Redis安装及基本数据类型,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧 ...

    liuyang04102019-11-13
  • RedisNestJS+Redis实现缓存步骤详解

    NestJS+Redis实现缓存步骤详解

    这篇文章主要介绍了NestJS+Redis实现缓存,本文分步骤给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...

    老胡Andy10682021-09-18
  • Rediswindows下使用redis requirepass认证不起作用的解决方法

    windows下使用redis requirepass认证不起作用的解决方法

    今天小编就为大家分享一篇windows下使用redis requirepass认证不起作用的解决方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧 ...

    Winyu_4332019-11-13
  • RedisRedis数据类型string和Hash详解

    Redis数据类型string和Hash详解

    大家都知道Redis中有五大数据类型分别是String、List、Set、Hash和Zset,本文给大家分享Redis数据类型string和Hash的相关操作,感兴趣的朋友跟随小编一起看看吧...

    灰小猿6932022-03-05
  • RedisRedis可视化工具Redis Desktop Manager的具体使用

    Redis可视化工具Redis Desktop Manager的具体使用

    本文主要介绍了Redis可视化工具Redis Desktop Manager的具体使用,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    老刀聊JAVA10862022-01-24
  • RedisRedis缓存常用4种策略原理详解

    Redis缓存常用4种策略原理详解

    这篇文章主要介绍了Redis缓存常用4种策略原理详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参...

    Tracydzf12752020-08-04
  • RedisRedis3.2.6配置文件详细中文说明

    Redis3.2.6配置文件详细中文说明

    本文为大家分享了Redis3.2.6配置文件详细中文说明,非常详细收藏起来以后工作有用 ...

    52PHP5112019-11-18
  • Redis详解Redis 数据类型

    详解Redis 数据类型

    这篇文章主要介绍了Redis 数据类型的相关资料,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下 ...

    菜鸟教程4652020-08-04