第十七章_Redis布隆过滤器BloomFilter实战

news2024/9/19 13:05:03

是什么

一句话

由一个初值都为零的bit数组和多个哈希函数构成,用来快速判断集合中是否存在某个元素

设计思想 

目的
减少内存占用
方式
不保存数据信息,只是在内存中做一个是否存在的标记flag

本质就是判断具体数据是否存在于一个大的集合中

备注 

布隆过滤器是一种类似set的数据结构,只是统计结果在巨量数据下有点小瑕疵,不够完美。

布隆过滤器(英语:Bloom Filter)是 1970 年由布隆提出的。

它实际上是一个很长的二进制数组(00000000)+一系列随机hash算法映射函数,主要用于判断一个元素是否在集合中。

通常我们会遇到很多要判断一个元素是否在某个集合中的业务场景,一般想到的是将集合中所有元素保存起来,然后通过比较确定。

链表、树、哈希表等等数据结构都是这种思路。但是随着集合中元素的增加,我们需要的存储空间也会呈现线性增长,最终达到瓶颈。同时检索速度也越来越慢,上述三种结构的检索时间复杂度分别为O(n),O(logn),O(1)。这个时候,布隆过滤器(Bloom Filter)就应运而生

能做什么(特点考点)

高效地插入和查询,占用空间少,返回的结果是不确定性+不够完美。 

目的
减少内存占用
方式
不保存数据信息,只是在内存中做一个是否存在的标记flag

重点

一个元素如果判断结果:存在时,元素不一定存在,但是判断结果为不存在时,则一定不存在

布隆过滤器可以添加元素,但是不能删除元素,由于涉及hashcode判断依据,删掉元素会导致误判率增加

小总结

有,是可能有

无,是肯定无

可以保证的是,如果布隆过滤器判断一个元素不在一个集合中,那这个元素一定不会在集合中

布隆过滤器原理

布隆过滤器实现原理和数据结构

原理

布隆过滤器原理

布隆过滤器(Bloom Filter) 是一种专门用来解决去重问题的高级数据结构。

实质就是一个大型位数组和几个不同的无偏hash函数(无偏表示分布均匀)。由一个初值都为零的bit数组和多个个哈希函数构成,用来快速判断某个数据是否存在。但是跟 HyperLogLog 一样,它也一样有那么一点点不精确,也存在一定的误判概率

添加key、查询key 

添加key时

使用多个hash函数对key进行hash运算得到一个整数索引值,对位数组长度进行取模运算得到一个位置,每个hash函数都会得到一个不同的位置,将这几个位置都置1就完成了add操作。

查询key时

只要有其中一位是零就表示这个key不存在,但如果都是1,则不一定存在对应的key。

结论:有,是可能有                      无,是肯定无

hash冲突导致数据不精准

当有变量被加入集合时,通过N个映射函数将这个变量映射成位图中的N个点,

把它们置为 1(假定有两个变量都通过 3 个映射函数)。

查询某个变量的时候我们只要看看这些点是不是都是 1, 就可以大概率知道集合中有没有它了

如果这些点, 有任何一个为零则被查询变量一定不在,
如果都是 1,则被查询变量很 可能存在,
为什么说是可能存在,而不是一定存在呢?那是因为映射函数本身就是散列函数,散列函数是会有碰撞的。(见上图3号坑两个对象都1)

查询某个变量的时候我们只要看看这些点是不是都是 1, 就可以大概率知道集合中有没有它了

hash冲突导致数据不精准2 

哈希函数

哈希函数的概念是:将任意大小的输入数据转换成特定大小的输出数据的函数,转换后的数据称为哈希值或哈希编码,也叫散列值

如果两个散列值是不相同的(根据同一函数)那么这两个散列值的原始输入也是不相同的。

这个特性是散列函数具有确定性的结果,具有这种性质的散列函数称为单向散列函数。

散列函数的输入和输出不是唯一对应关系的,如果两个散列值相同,两个输入值很可能是相同的,但也可能不同,这种情况称为“散列碰撞(collision)”。

用 hash表存储大数据量时,空间效率还是很低,当只有一个 hash 函数时,还很容易发生哈希碰撞。

Java中hash冲突java案例

public class HashCodeConflictDemo {

    public static void main(String[] args) {
        Set<Integer> hashCodeSet = new HashSet<>();

        for (int i = 0; i < 200000; i++) {
            int hashCode = new Object().hashCode();

            if(hashCodeSet.contains(hashCode)) {
                System.out.println("出现了重复的hashcode: " + hashCode+"\t 运行到" + i);
                break;
            }

            hashCodeSet.add(hashCode);
        }

        System.out.println("Aa".hashCode());
        System.out.println("BB".hashCode());
        System.out.println("柳柴".hashCode());
        System.out.println("柴柕".hashCode());
    }

}

 

使用3步骤

初始化bitmap

布隆过滤器 本质上 是由长度为 m 的位向量或位列表(仅包含 0 或 1 位值的列表)组成,最初所有的值均设置为 0

添加占坑位 

当我们向布隆过滤器中添加数据时,为了尽量地址不冲突,会使用多个 hash 函数对 key 进行运算,算得一个下标索引值,然后对位数组长度进行取模运算得到一个位置,每个 hash 函数都会算得一个不同的位置。再把位数组的这几个位置都置为 1 就完成了 add 操作。

例如,我们添加一个字符串wmyskxz,对字符串进行多次hash(key) → 取模运行→ 得到坑位

判断是否存在

向布隆过滤器查询某个key是否存在时,先把这个 key 通过相同的多个 hash 函数进行运算,查看对应的位置是否都为 1,

只要有一个位为零,那么说明布隆过滤器中这个 key 不存在;

如果这几个位置全都是 1,那么说明极有可能存在;

因为这些位置的 1 可能是因为其他的 key 存在导致的,也就是前面说过的hash冲突。。。。。

就比如我们在 add 了字符串wmyskxz数据之后,很明显下面1/3/5 这几个位置的 1 是因为第一次添加的 wmyskxz 而导致的;

此时我们查询一个没添加过的不存在的字符串inexistent-key,它有可能计算后坑位也是1/3/5 ,这就是误判了......

布隆过滤器误判率,为什么不要删除

布隆过滤器的误判是指多个输入经过哈希之后在相同的bit位置1了,这样就无法判断究竟是哪个输入产生的,因此误判的根源在于相同的 bit 位被多次映射且置 1。

这种情况也造成了布隆过滤器的删除问题,因为布隆过滤器的每一个 bit 并不是独占的,很有可能多个元素共享了某一位

如果我们直接删除这一位的话,会影响其他的元素

特性

布隆过滤器可以添加元素,但是不能删除元素。因为删掉元素会导致误判率增加。

小总结

是否存在:有,是很可能有,无,是肯定无,100%无。

使用时最好不要让实际元素数量远大于初始化数量,一次给够避免扩容。

当实际元素数量超过初始化数量时,应该对布隆过滤器进行重建,重新分配一个 size 更大的过滤器,再将所有的历史元素批量 add 进行。

布隆过滤器的使用场景

解决缓存穿透的问题,和redis结合bitmap使用 

缓存穿透是什么

一般情况下,先查询缓存redis是否有该条数据,缓存中没有时,再查询数据库。

当数据库也不存在该条数据时,每次查询都要访问数据库,这就是缓存穿透。

缓存透带来的问题是,当有大量请求查询数据库不存在的数据时,就会给数据库带来压力,甚至会拖垮数据库。

可以使用布隆过滤器解决缓存穿透的问题

把已存在数据的key存在布隆过滤器中,相当于redis前面挡着一个布隆过滤器。

当有新的请求时,先到布隆过滤器中查询是否存在:

如果布隆过滤器中不存在该条数据则直接返回;

如果布隆过滤器中已存在,才去查询缓存redis,如果redis里没查询到则再查询Mysql数据库。

黑名单校验,识别垃圾邮件 

发现存在黑名单中的,就执行特定操作。比如:识别垃圾邮件,只要是邮箱在黑名单中的邮件,就识别为垃圾邮件。

假设黑名单的数量是数以亿计的,存放起来就是非常耗费存储空间的,布隆过滤器则是一个较好的解决方案。

把所有黑名单都放在布隆过滤器中,在收到邮件时,判断邮件地址是否在布隆过滤器中即可。

安全连接网址,全球上10亿的网址判断

。。。。。。

尝试手写布隆过滤器,结合bitmap自研一下体会思想

结合bitmap类型手写一个简单的布隆过滤器,体会设计思想 

整体架构

步骤设计 

redis的setbit/getbit

setBit的构建过程 

  1. @PostConstruct初始化白名单数据
  2. 计算元素的hash值
  3. 通过上一步hash值算出对应的二进制数组的坑位
  4. 将对应坑位的值的修改为数字1,表示存在

getBit查询是否存在

  1. 计算元素的hash值
  2. 通过上一步hash值算出对应的二进制数组的坑位
  3. 返回对应坑位的值,零表示无,1表示存在

springboot+redis+mybatis案例基础与一键编码环境整合

MyBatis 通用 Mapper4

mybatis-generator官网

MyBatis 通用 Mapper4官网

一键生成

t_customer用户表SQL

CREATE TABLE `t_customer` (

  `id` int(20) NOT NULL AUTO_INCREMENT,

  `cname` varchar(50) NOT NULL,

  `age` int(10) NOT NULL,

  `phone` varchar(20) NOT NULL,

  `sex` tinyint(4) NOT NULL,

  `birth` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

  PRIMARY KEY (`id`),

  KEY `idx_cname` (`cname`)

) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4;

建springboot的Module

mybatis_generator

改POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.atguigu.redis7</groupId>
    <artifactId>mybatis_generator</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.10</version>
        <relativePath/>
    </parent>

    <properties>
        <!--  依赖版本号 -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <java.version>1.8</java.version>
        <hutool.version>5.5.8</hutool.version>
        <druid.version>1.1.18</druid.version>
        <mapper.version>4.1.5</mapper.version>
        <pagehelper.version>5.1.4</pagehelper.version>
        <mysql.version>5.1.39</mysql.version>
        <swagger2.version>2.9.2</swagger2.version>
        <swagger-ui.version>2.9.2</swagger-ui.version>
        <mybatis.spring.version>2.1.3</mybatis.spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--Mybatis 通用mapper tk单独使用,自己带着版本号-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>

        <!--mybatis-spring-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis.spring.version}</version>
        </dependency>

        <!-- Mybatis Generator -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.4.0</version>
            <scope>compile</scope>
            <optional>true</optional>
        </dependency>

        <!--通用Mapper-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <version>${mapper.version}</version>
        </dependency>

        <!--persistence-->
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0.2</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>${basedir}/src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>

            <resource>
                <directory>${basedir}/src/main/resources</directory>
            </resource>
        </resources>

        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.6</version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>

                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>${mysql.version}</version>
                    </dependency>

                    <dependency>
                        <groupId>tk.mybatis</groupId>
                        <artifactId>mapper</artifactId>
                        <version>${mapper.version}</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

mgb配置相关src\main\resources路径下新建

config.properties(内容):

#t_customer表包名
package.name=com.test.redis7

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/bigdata
jdbc.user=root
jdbc.password=123456

generatorConfig.xml(内容):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <properties resource="config.properties"/>

    <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>

        <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <property name="mappers" value="tk.mybatis.mapper.common.Mapper"/>
            <property name="caseSensitive" value="true"/>
        </plugin>

        <jdbcConnection driverClass="${jdbc.driverClass}"
                        connectionURL="${jdbc.url}"
                        userId="${jdbc.user}"
                        password="${jdbc.password}">
        </jdbcConnection>

        <javaModelGenerator targetPackage="${package.name}.entities" targetProject="src/main/java"/>

        <sqlMapGenerator targetPackage="${package.name}.mapper" targetProject="src/main/java"/>

        <javaClientGenerator targetPackage="${package.name}.mapper" targetProject="src/main/java" type="XMLMAPPER"/>

        <table tableName="t_customer" domainObjectName="Customer">
            <generatedKey column="id" sqlStatement="JDBC"/>
        </table>
    </context>
</generatorConfiguration>

一键生成

双击插件mybatis-generator:gererate,一键生成,生成entity+mapper接口+xml实现SQL

SpringBoot + Mybatis + Redis缓存实战编码

建Module

改造redis7_study工程

POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.test.redis7</groupId>
    <artifactId>redis7_study</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.10</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <junit.version>4.12</junit.version>
        <log4j.version>1.2.17</log4j.version>
        <lombok.version>1.16.18</lombok.version>
    </properties>

    <dependencies>
        <!--SpringBoot通用依赖模块-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--jedis-->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>4.3.1</version>
        </dependency>

        <!--lettuce-->
        <!--<dependency>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
            <version>6.2.1.RELEASE</version>
        </dependency>-->

        <!--SpringBoot与Redis整合依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>

        <!--swagger2-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

        <!--Mysql数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <!--SpringBoot集成druid连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>

        <!--mybatis和springboot整合-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>

        <!--hutool-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.2.3</version>
        </dependency>

        <!--persistence-->
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0.2</version>
        </dependency>

        <!--通用Mapper-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <version>4.1.5</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>

        <!--通用基础配置junit/devtools/test/log4j/lombok/-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

YML

server.port=7777

spring.application.name=redis7_study

# ========================logging=====================
logging.level.root=info
logging.level.com.test.redis7=info
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger- %msg%n 

logging.file.name=D:/mylogs2023/redis7_study.log
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger- %msg%n

# ========================swagger=====================
spring.swagger2.enabled=true
#在springboot2.6.X结合swagger2.9.X会提示documentationPluginsBootstrapper空指针异常,
#原因是在springboot2.6.X中将SpringMVC默认路径匹配策略从AntPathMatcher更改为PathPatternParser,
# 导致出错,解决办法是matching-strategy切换回之前ant_path_matcher
spring.mvc.pathmatch.matching-strategy=ant_path_matcher

# ========================redis单机=====================
spring.redis.database=0
# 修改为自己真实IP
spring.redis.host=192.168.111.185
spring.redis.port=6379
spring.redis.password=111111
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=-1ms
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0

# ========================alibaba.druid=====================
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/bigdata?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.druid.test-while-idle=false

# ========================mybatis===================
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.test.redis7.entities

# ========================redis集群=====================
#spring.redis.password=111111
## 获取失败 最大重定向次数
#spring.redis.cluster.max-redirects=3
#spring.redis.lettuce.pool.max-active=8
#spring.redis.lettuce.pool.max-wait=-1ms
#spring.redis.lettuce.pool.max-idle=8
#spring.redis.lettuce.pool.min-idle=0
##支持集群拓扑动态感应刷新,自适应拓扑刷新是否使用所有可用的更新,默认false关闭
#spring.redis.lettuce.cluster.refresh.adaptive=true
##定时刷新
#spring.redis.lettuce.cluster.refresh.period=2000
#spring.redis.cluster.nodes=192.168.111.185:6381,192.168.111.185:6382,192.168.111.172:6383,192.168.111.172:6384,192.168.111.184:6385,192.168.111.184:6386

\src\main\resources\目录下新建mapper文件夹并拷贝CustomerMapper.xml

主启动

package com.test.redis7;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;

/**
 * @auther admin
 */
@SpringBootApplication
@MapperScan("com.test.redis7.mapper") 
public class Redis7Study7777 {

    public static void main(String[] args) {
        SpringApplication.run(Redis7Study7777.class, args);
    }

}

业务类

数据库表t_customer是否OK

entity上一步自动生成的拷贝过来

package com.test.redis7.entities;

import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Date;

@Table(name = "t_customer")
public class Customer implements Serializable {

    @Id
    @GeneratedValue(generator = "JDBC")
    private Integer id;

    private String cname;

    private Integer age;

    private String phone;

    private Byte sex;

    private Date birth;

    public Customer() {

    }

    public Customer(Integer id, String cname) {
        this.id = id;
        this.cname = cname;
    }

    /**
     * @return id 主键id
     */
    public Integer getId() {
        return id;
    }

    /**
     * @param id 主键id
     */
    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * @return cname 别名
     */
    public String getCname() {
        return cname;
    }

    /**
     * @param cname 别名
     */
    public void setCname(String cname) {
        this.cname = cname;
    }

    /**
     * @return age 年龄
     */
    public Integer getAge() {
        return age;
    }

    /**
     * @param age 年龄
     */
    public void setAge(Integer age) {
        this.age = age;
    }

    /**
     * @return phone 电话
     */
    public String getPhone() {
        return phone;
    }

    /**
     * @param phone 电话
     */
    public void setPhone(String phone) {
        this.phone = phone;
    }

    /**
     * @return sex 性别
     */
    public Byte getSex() {
        return sex;
    }

    /**
     * @param sex 性别
     */
    public void setSex(Byte sex) {
        this.sex = sex;
    }

    /**
     * @return birth 生日
     */
    public Date getBirth() {
        return birth;
    }

    /**
     * @param birth 生日
     */
    public void setBirth(Date birth) {
        this.birth = birth;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", cname='" + cname + '\'' +
                ", age=" + age +
                ", phone='" + phone + '\'' +
                ", sex=" + sex +
                ", birth=" + birth +
                '}';
    }

}

mapper接口

package com.test.redis7.mapper;

import com.test.redis7.entities.Customer;
import tk.mybatis.mapper.common.Mapper;

public interface CustomerMapper extends Mapper<Customer> {

}

mapperSQL文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.test.redis7.mapper.CustomerMapper">
  <resultMap id="BaseResultMap" type="com.test.redis7.entities.Customer">
    <!--
      WARNING - @mbg.generated
    -->
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="cname" jdbcType="VARCHAR" property="cname" />
    <result column="age" jdbcType="INTEGER" property="age" />
    <result column="phone" jdbcType="VARCHAR" property="phone" />
    <result column="sex" jdbcType="TINYINT" property="sex" />
    <result column="birth" jdbcType="TIMESTAMP" property="birth" />
  </resultMap>
</mapper>

service接口CustomerSerivce

package com.test.redis7.service;

import com.test.redis7.entities.Customer;

public interface CustomerSerivce {

    void addCustomer(Customer customer);

    Customer findCustomerById(Integer customerId);

}

service实现类CustomerSerivceImpl

package com.test.redis7.service.impl;

import com.test.redis7.service.CustomerSerivce;

import com.test.redis7.entities.Customer;
import com.test.redis7.mapper.CustomerMapper;
import com.test.redis7.utils.CheckUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @auther admin
 */
@Slf4j
@Service
public class CustomerSerivceImpl implements CustomerSerivce {

    public static final String CACHE_KEY_CUSTOMER = "customer:";

    @Resource
    private CustomerMapper customerMapper;

    @Resource
    private RedisTemplate redisTemplate;

    public void addCustomer(Customer customer) {
        int i = customerMapper.insertSelective(customer);

        if(i > 0) {
            //到数据库里面,重新捞出新数据出来,做缓存
            customer = customerMapper.selectByPrimaryKey(customer.getId());
            //缓存key
            String key = CACHE_KEY_CUSTOMER + customer.getId();
            //往mysql里面插入成功随后再从mysql查询出来,再插入redis
            redisTemplate.opsForValue().set(key, customer);
        }
    }

    public Customer findCustomerById(Integer customerId) {
        Customer customer = null;
        //缓存key的名称
        String key=CACHE_KEY_CUSTOMER + customerId;
        //1 查询redis
        customer = (Customer) redisTemplate.opsForValue().get(key);

        //redis无,进一步查询mysql
        if(customer == null){
            //2 从mysql查出来customer
            customer = customerMapper.selectByPrimaryKey(customerId);

            // mysql有,redis无
            if (customer != null) {
                //3 把mysql捞到的数据写入redis,方便下次查询能redis命中。
                redisTemplate.opsForValue().set(key, customer);
            }
        }

        return customer;
    }

}

controller

package com.test.redis7.controller;

import com.test.redis7.entities.Customer;
import com.test.redis7.service.CustomerSerivce;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Random;
import java.util.Date;
import java.util.concurrent.ExecutionException;

/**
 * @auther admin
 */
@Slf4j
@RestController
@Api(tags = "客户Customer接口+布隆过滤器讲解")
public class CustomerController {

    @Resource 
    private CustomerSerivce customerSerivce;

    @ApiOperation("数据库初始化2条Customer数据")
    @RequestMapping(value = "/customer/add", method = RequestMethod.POST)
    public void addCustomer() {
        for (int i = 0; i < 2; i++) {
            Customer customer = new Customer();
            customer.setCname("customer" + i);
            customer.setAge(new Random().nextInt(30) + 1);
            customer.setPhone("1381111xxxx");
            customer.setSex((byte) new Random().nextInt(2));                             
            customer.setBirth(Date.from(LocalDateTime.now()
              .atZone(ZoneId.systemDefault())
              .toInstant()));
            customerSerivce.addCustomer(customer);
        }
    }

    @ApiOperation("单个用户查询,按customerid查用户信息")
    @RequestMapping(value = "/customer/{id}", method = RequestMethod.GET)
    public Customer findCustomerById(@PathVariable int id) {
        return customerSerivce.findCustomerById(id);
    }

}

启动测试Swagger是否OK

swagger文档地址:http://localhost:你的微服务端口/swagger-ui.html#/

新增布隆过滤器案例

code

BloomFilterInit(白名单)

package com.test.redis7.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @auther admin
 * 布隆过滤器白名单初始化工具类,一开始就设置一部分数据为白名单所有,
 * 白名单业务默认规定:布隆过滤器有,redis也有。
 */
@Slf4j
@Component
public class BloomFilterInit {

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 初始化白名单数据,故意差异化数据演示效果......
     */
    @PostConstruct
    public void init() {
        //白名单客户预加载到布隆过滤器
        String uid = "customer:12";
        //1 计算hashcode,由于可能有负数,直接取绝对值
        int hashValue = Math.abs(uid.hashCode());
        //2 通过hashValue和2的32次方取余后,获得对应的下标坑位
        long index = (long) (hashValue % Math.pow(2, 32));
        log.info(uid+" 对应------坑位index:{}", index);
        //3 设置redis里面bitmap对应坑位,该有值设置为1
        redisTemplate.opsForValue().setBit("whitelistCustomer", index, true);
    }

}
 

CheckUtils

package com.test.redis7.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @auther admin
 */
@Slf4j
@Component
public class CheckUtils {

    @Resource
    private RedisTemplate redisTemplate;

    public boolean checkWithBloomFilter(String checkItem, String key) {
        int hashValue = Math.abs(key.hashCode());
        long index = (long) (hashValue % Math.pow(2, 32));
        boolean existOK = redisTemplate.opsForValue().getBit(checkItem, index);
        log.info("----->key:" + key + "\t对应坑位index:" + index + "\t是否存在:" + existOK);
        return existOK;
    }

}

CustomerSerivce 

package com.test.redis7.service;

import com.test.redis7.entities.Customer;

public interface CustomerSerivce {

    void addCustomer(Customer customer);

    Customer findCustomerById(Integer customerId);

    Customer findCustomerByIdWithBloomFilter(Integer customerId);

}

CustomerSerivceImpl

package com.test.redis7.service;

import com.test.redis7.service.CustomerSerivce;

import com.test.redis7.entities.Customer;
import com.test.redis7.mapper.CustomerMapper;
import com.test.redis7.utils.CheckUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @auther admin
 */
@Slf4j
@Service
public class CustomerSerivce implements CustomerSerivce {

    public static final String CACHE_KEY_CUSTOMER = "customer:";

    @Resource
    private CustomerMapper customerMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private CheckUtils checkUtils;

    public void addCustomer(Customer customer){
        int i = customerMapper.insertSelective(customer);

        if(i > 0) {
            //到数据库里面,重新捞出新数据出来,做缓存
            customer = customerMapper.selectByPrimaryKey(customer.getId());
            //缓存key
            String key=CACHE_KEY_CUSTOMER + customer.getId();
            //往mysql里面插入成功随后再从mysql查询出来,再插入redis
            redisTemplate.opsForValue().set(key, customer);
        }
    }

    public Customer findCustomerById(Integer customerId){
        Customer customer = null;

        //缓存key的名称
        String key=CACHE_KEY_CUSTOMER+customerId;

        //1 查询redis
        customer = (Customer) redisTemplate.opsForValue().get(key);

        //redis无,进一步查询mysql
        if(customer == null) {
            //2 从mysql查出来customer
            customer=customerMapper.selectByPrimaryKey(customerId);

            // mysql有,redis无
            if (customer != null) {
                //3 把mysql捞到的数据写入redis,方便下次查询能redis命中。
                redisTemplate.opsForValue().set(key, customer);
            }
        }

        return customer;
    }

    /**
     * BloomFilter → redis → mysql
     * 白名单:whitelistCustomer
     * @param customerId 客户主键id
     * @return 客户信息
     */
    public Customer findCustomerByIdWithBloomFilter(Integer customerId) {
        Customer customer = null;

        //缓存key的名称
        String key = CACHE_KEY_CUSTOMER + customerId;

        //布隆过滤器check,无是绝对无,有是可能有
        //===============================================

        if(!checkUtils.checkWithBloomFilter("whitelistCustomer", key)) {
            log.info("白名单无此顾客信息:{}", key);
            return null;
        }

        //===============================================

        //1 查询redis
        customer = (Customer) redisTemplate.opsForValue().get(key);

        //redis无,进一步查询mysql
        if (customer == null) {
            //2 从mysql查出来customer
            customer = customerMapper.selectByPrimaryKey(customerId);

            // mysql有,redis无
            if (customer != null) {
                //3 把mysql捞到的数据写入redis,方便下次查询能redis命中。
                redisTemplate.opsForValue().set(key, customer);
            }
        }

        return customer;
    }

}

CustomerController

package com.test.redis7.controller;

import com.test.redis7.entities.Customer;
import com.test.redis7.service.CustomerSerivce;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Random;
import java.util.Date;
import java.util.concurrent.ExecutionException;

/**
 * @auther admin
 */
@Slf4j
@RestController
@Api(tags = "客户Customer接口+布隆过滤器讲解")
public class CustomerController {

    @Resource 
    private CustomerSerivce customerSerivce;

    @ApiOperation("数据库初始化2条Customer数据")
    @RequestMapping(value = "/customer/add", method = RequestMethod.POST)
    public void addCustomer() {
        for (int i = 0; i < 2; i++) {
            Customer customer = new Customer();
            customer.setCname("customer" + i);
            customer.setAge(new Random().nextInt(30) + 1);
            customer.setPhone("1381111xxxx");
            customer.setSex((byte) new Random().nextInt(2));
            customer.setBirth(Date.from(LocalDateTime.now()
                .atZone(ZoneId.systemDefault())
                .toInstant()));
            customerSerivce.addCustomer(customer);
        }
    }

    @ApiOperation("单个用户查询,按customerid查用户信息")
    @RequestMapping(value = "/customer/{id}", method = RequestMethod.GET)
    public Customer findCustomerById(@PathVariable int id) {
        return customerSerivce.findCustomerById(id);
    }

    @ApiOperation("BloomFilter案例讲解")
    @RequestMapping(value = "/customerbloomfilter/{id}", method = RequestMethod.GET)
    public Customer findCustomerByIdWithBloomFilter(@PathVariable int id) throws ExecutionException, InterruptedException {
        return customerSerivce.findCustomerByIdWithBloomFilter(id);
    }

}

测试说明

布隆过滤器有,redis有

布隆过滤器有,redis无

布隆过滤器无,直接返回,不再继续走下去

布隆过滤器优缺点 

优点 

高效地插入和查询,内存占用bit空间少

缺点

不能删除元素。

因为删掉元素会导致误判率增加,因为hash冲突同一个位置可能存的东西是多个共有的,你删除一个元素的同时可能也把其它的删除了。

存在误判,不能精准过滤:有,是很可能有;无,是肯定无,100%无。

布谷鸟过滤器(了解)

为了解决布隆过滤器不能删除元素的问题,布谷鸟过滤器横空出世。

论文《Cuckoo Filter:Better Than Bloom》。

作者将布谷鸟过滤器和布隆过滤器进行了深入的对比。

不过,了解的一些企业,目前用的比较多比较成熟的就是布隆过滤器,暂时没有升级换代的需求。

大厂真实需求+面试题

现有50亿个电话号码,现有10万个电话号码,如何要快速准确的判断这些电话号码是否已经存在?

让你判断在50亿记录中有没有,不是让你存。 有就返回1,没有返回零。

1、通过数据库查询-------实现快速有点难。

2、数据预放到内存集合中:50亿*8字节大约40G,内存太大了。

判断是否存在,布隆过滤器了解过吗?

安全连接网址,全球数10亿的网址判断?

黑名单校验,识别垃圾邮件?

白名单校验,识别出合法用户进行后续处理?

。。。。。。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/544284.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

好兄弟单身?这不得用python来帮他脱离苦海

明天什么节日 &#xff1f;明天谁过节 &#xff1f; 是你吗&#xff0c;还是你的朋友 &#xff1f;如果是你的话&#xff0c;那咱就帮帮朋友&#xff0c;到年龄的咱就直接相亲呗 赠人玫瑰 手留余香 好人做到底&#xff0c;来让朋友体验体验恋爱的感觉~ 今天就带你们来爬爬相亲…

BoostSearch搜索引擎

今天讲的项目是基于C的Boost库的站内搜索引擎。因为Boost库内没有搜索关键字功能&#xff0c;所以在这里我们来手动实现一个这样的搜索引擎。当用户在输入框输入要查询的关键字后&#xff0c;就会快速查询出相关的 boost 库中的文档&#xff0c;弥补 boost 在线文档没有搜索功能…

C++进阶——mapset的使用

C进阶——map&set的使用 关联式容器 在初阶阶段&#xff0c;我们已经接触过STL中的部分容器&#xff0c;比如&#xff1a;vector、list、deque、forward_list(C11)等&#xff0c;这 些容器统称为序列式容器&#xff0c;因为其底层为线性序列的数据结构&#xff0c;里面存…

chatgpt赋能Python-python2的阶乘

Python2中的阶乘 Python是一种高级编程语言&#xff0c;它可以用来编写各种各样的程序。在Python中&#xff0c;阶乘是一个经常用到的数学概念&#xff0c;由于其强大的计算能力和易学易用的特点&#xff0c;Python成为了计算阶乘的一个很好的工具。在这篇文章中&#xff0c;我…

MySql 数据库的锁机制和原理

MySQL是一种流行的关系型数据库管理系统&#xff0c;广泛应用于各种Web应用程序和企业级应用程序中。在MySQL中&#xff0c;锁是一种用于控制并发访问的机制&#xff0c;它可以保证数据的一致性和完整性。本文将介绍MySQL的锁机制及原理&#xff0c;包括锁的类型、级别和实现原…

Idea配置moven

moven的下载与安装 https://maven.apache.org/download.cgi 解压到指定位置&#xff0c;配置环境变量 编辑系统变量Path&#xff0c;添加变量值&#xff1a;%MAVEN_HOME%\bin winr输入cmd输入 mvn -v 出现上述界面&#xff0c;则表示成功安装Maven 新建一个文件夹作为本地…

[入门必看]数据结构5.5:树与二叉树的应用

[入门必看]数据结构5.5&#xff1a;树与二叉树的应用 第五章 树与二叉树5.5 树与二叉树的应用知识总览5.5.1 哈夫曼树5.5.2_1 并查集5.5.2_2 并查集的进一步优化 5.5.1 哈夫曼树带权路径长度哈夫曼树的定义哈夫曼树的构造哈夫曼编码应用&#xff1a;英文字母频次 5.5.2_1 并查集…

MybatisPlus详解

文章目录 1.MyBatisPlus的介绍1.1 MybatisPlus的特性讲解1.2 支持的数据库1.3 MybatisPlus的日志 2.映射2.1 自动映射规则2.2 表映射2.3 字段映射2.4 字段失效2.5 视图属性 3. 条件构造器3.1 等值查询3.1.1 eq3.1.2 allEq3.1.3 ne 不等于 3.2 范围查询3.2.1 gt 大于3.2.2 ge 大…

[Nacos] Nacos Client重要Api (一)

Instance&#xff1a;实例&#xff0c;代表一个Nacos Client主机实例。ServiceInfo&#xff1a;微服务信息实例。其包含着一个Instance列表。NamingService&#xff1a; 该接口只有一个实现类&#xff0c;NacosNamingService。通过这个类的实例&#xff0c;可以完成Client与Ser…

数据结构篇六:二叉树

文章目录 前言1. 树的概念及结构1.1 树的概念1.2 树的相关概念1.3 树的结构 2. 二叉树的概念及结构2.1 二叉树的概念2.2 特殊的二叉树2.3 二叉树的性质2.4 二叉树的存储结构 3. 二叉树的顺序结构及实现3.1 二叉树的顺序结构3.2 堆的概念及结构3.3 堆的实现3.3.1 堆的创建3.3.2 …

如何在命令提示符中备份Windows设备驱动程序

如果清理安装Windows,则需要为系统中的每个设备安装驱动程序。制造商可能不再提供其中一些设备驱动程序,或者你放错了制造商的驱动程序安装文件备份。 在进行干净安装之前备份设备驱动程序是个好主意,这样之后就可以根据需要轻松恢复这些驱动程序,我们可以按以下方法来备份…

跟着chatGPT学习:kubernetes中的Reflector、list-watcher、informer等概念

以下是我跟chatGPT学习kubernetes中Reflector、list-watcher、informer等的概念的过程 不敢保证chatGPT回答的百分之百准确。但是&#xff0c;确实帮助我了我理解&#xff01; 最终学习的是下面的图&#xff0c; 1、在kubernetes中Reflector原理&#xff1f; 在Kubernetes…

PDF工具Adobe Arcrobat Pro DC下载安装教程

wx供重浩&#xff1a;创享日记 对话框发送&#xff1a;adobe 免费获取Adobe Arcrobat Pro DC安装包 Acrobat是一款PDF&#xff08;Portable Document Format&#xff0c;便携式文档格式&#xff09;编辑软件。借助它&#xff0c;您可以以PDF格式制作和保存你的文档 &#xff0c…

Oracle数据库服务器中了locked1勒索病毒的方式与破坏用友nchome配置文件方式

随着计算机技术的不断发展&#xff0c;网络安全问题也变得日益严峻。其中&#xff0c;勒索病毒就是一种非常危险的网络威胁。它可以通过加密受害者的文件或数据库&#xff0c;使其无法正常使用&#xff0c;然后向受害者勒索赎金以解密文件。而最近收到很多企业的求助&#xff0…

什么是语音识别的语音助手?

前言 语音助手已经成为现代生活中不可或缺的一部分。人们可以通过语音助手进行各种操作&#xff0c;如查询天气、播放音乐、发送短信等。语音助手的核心技术是语音识别。本文将详细介绍语音识别的语音助手。 语音识别的基本原理 语音识别是将语音信号转换为文本的技术。语音识…

Centos7升级gcc、g++版本

Centos7默认的 gcc版本是 4.8.5 默认使用yum install gcc安装出来的gcc版本也是是4.8.5。 1.首先查看自己的 gcc 版本 gcc -v g -v如果出现&#xff1a;bash: g: 未找到命令... 则安装g&#xff1a;遇到暂停时&#xff0c;输入y继续安装 yum install gcc-c然后输入&#xf…

38、Solr Integration(2)Install Solr

文章目录 38、Solr Integration&#xff08;2&#xff09;Install Solr下载启动创建Core填充数据搜索测试 38、Solr Integration&#xff08;2&#xff09;Install Solr 下载 进入Solr下载页面Solr Downloads - Apache Solr 下载需要的版本&#xff0c;这里下载最新版9.2.1&a…

为什么我们应该选择Renderbus瑞云渲染进行 EEVEE 渲染?

在某些情况下&#xff0c;用户需要高精度、快速的渲染&#xff0c;而 EEVEE的诞生就是为了满足这种需求。Eevee&#xff08;Extra Easy Virtual Environment Engine&#xff09;是 Blender 最新的内部渲染引擎&#xff0c;由用于 Epic Games 开发的虚幻引擎的相同代码提供支持…

内存基础知识

概述 内存可存放数据。程序执行前需要先将外存中的数据放到内存中才能被CPU处理&#xff0c;因为CPU处理速度过快&#xff0c;而从硬盘读取数据较慢&#xff0c;所以内存是为了缓和CPU和硬盘之间的读取速度矛盾 在多道程序环境下&#xff0c;系统中会有多个程序并发执行&…

Git——C站最详细的Git教程,一篇学会Git(window\linux通用)

Git——C站最详细的Git教程&#xff0c;一篇学会Git(window\linux通用) 文章目录 Git——C站最详细的Git教程&#xff0c;一篇学会Git(window\linux通用)Git简介Git作用为什么要进行源代码管理?Git的诞生Git管理源代码特点Git操作流程图解 工作区暂存区和仓库区工作区暂存区仓…