由一个初值都为零的bit数组和多个哈希函数构成,用来快速判断集合中是否存在某个元素
目的
方式
本质
布隆过滤器是一种类似 set 的数据结构,只是统计结果在巨量数据下有点小瑕疵,不够完美
高效地插入和查询,占用空间少,返回地结果是不确定性 + 不完美性
布隆过滤器可以添加元素,但是不能删除元素
布隆过滤器(Bloom Filter) 是一种专门用来解决去重问题的高级数据结构。
实质就是一个大型位数组和几个不同的无偏hash函数(无偏表示分布均匀)。由一个初值为零地bit数组和多个哈希函数构成,用来快速判断某个数据是否存在。但是跟HyperLogLog一样,他也有一点不精确,存在一定的误判概率
添加 key 时
查询 key 时
结论
hash 冲突导致数据不精准1
hash 冲突导致数据不精准2
对字符串进行多次hash(key) → 取模运行→ 得到坑位
缓存穿透是什么
一般情况下,先查询缓存redis是否有该条数据,缓存中没有时,再查询数据库。
当数据库也不存在该条数据时,每次查询都要访问数据库,这就是缓存穿透。
缓存透带来的问题是,当有大量请求查询数据库不存在的数据时,就会给数据库带来压力,甚至会拖垮数据库。
可以使用布隆过滤器解决缓存穿透的问题;
把已存在数据的key存在布隆过滤器中,相当于redis前面挡着一个布隆过滤器。
当有新的请求时,先到布隆过滤器中查询是否存在:
如果布隆过滤器中不存在该条数据则直接返回; 如果布隆过滤器中已存在,才去查询缓存redis,如果redis里没查询到则再查询Mysq|数据库
@PostConstruct
初始化白名单数据getBit
查询是否存在
使用Mapper4自动生成
建表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
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.xfcy</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
${basedir}/src/main/resources
org.springframework.boot
spring-boot-maven-plugin
org.projectlombok
lombok
org.mybatis.generator
mybatis-generator-maven-plugin
1.3.6
${basedir}/src/main/resources/generatorConfig.xml
true
true
mysql
mysql-connector-java
${mysql.version}
tk.mybatis
mapper
${mapper.version}
src/main/resources
#t_customer表包名
#com.xfcy 输自己用的包名 要不然不能直接cv到自己用的工程里
package.name=com.xfcy
jdbc.driverClass = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/db_boot
jdbc.user = root
jdbc.password =123456
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>
ps:生成这两个即可
整合redis
<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>
server.port=7070
# ========================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.238.111
spring.redis.port=6379
spring.redis.password=123456
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
# ========================logging=====================
logging.level.root=info
logging.level.com.atguigu.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
# ========================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/db_boot?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.xfcy.entities
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;
/**
* customer 是有关简单手写布隆过滤器
*/
@MapperScan("com.xfcy.mapper") // import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
public class Redis7Study2Application {
public static void main(String[] args) {
SpringApplication.run(Redis7Study2Application.class, args);
}
}
布隆过滤器
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;
/**
* 布隆过滤器白名单初始化工具类,一开始就设置一部分数据为白名单所有
* 白名单业务默认规定:布隆过滤器有,redis 有可能有 布隆过滤器无 redis一定无
* 白名单业务默认规定:whitelistCustomer
*/
@Component
@Slf4j
public class BloomFilterInit {
@Resource
private RedisTemplate redisTemplate;
@PostConstruct // 初始化白名单数据
public void init() {
// 1.白名单客户加载到布隆过滤器
String key = "customer:11";
// 2.计算hashValue,由于存在计算出来负数的可能,取绝对值
int hashValue = Math.abs(key.hashCode());
// 3.通过hashValue 和 2的32次方后取余,获得对应的下标坑位
long index = (long) (hashValue % Math.pow(2, 32));
log.info(key + "对应的坑位 index: {}", index);
// 4.设置redis里面的bitmap对应类型的坑位,将该值设置为1
redisTemplate.opsForValue().setBit("whitelistCustomer", index, true);
}
}
import javax.annotation.Resource;
@Component
@Slf4j
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 +"对应坑位下标index:"+ index + "是否存在:" + existOK);
return existOK;
}
}
业务类
entity 拷贝生成的 Customer类
mapper 拷贝生成的CustomerMapper 类
src/main/resources/mapper 拷贝生成的 CustomerMapper.xml
service类 (个人修改了一部分 加上了双检加锁)
import com.xfcy.entities.Customer;
import com.xfcy.mapper.CustomerMapper;
import com.xfcy.utils.CheckUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
@Service
@Slf4j
public class CustomerService {
public static final String CACHE_KEY_CUSTOMER = "customer:";
@Resource
private CustomerMapper customerMapper;
@Resource
private RedisTemplate redisTemplate;
@Resource
private CheckUtils checkUtils;
/**
* 写操作
*
* @param customer
*/
public void addCustomer(Customer customer) {
int i = customerMapper.insertSelective(customer);
if (i > 0) {
// mysql 插入成功,需要重新查询一次将数据写进redis
Customer result = customerMapper.selectByPrimaryKey(customer.getId());
// redis缓存key
String key = CACHE_KEY_CUSTOMER + customer.getId();
// 写入redis
redisTemplate.opsForValue().set(key, result);
}
}
/**
* 读操作 + 双检加锁 + null缓存
*/
public Customer findCustomerById(Integer customerId) {
Customer customer = null;
// 缓存redis的key名称
String key = CACHE_KEY_CUSTOMER + customerId;
// 1.去redis上查询
customer = (Customer) redisTemplate.opsForValue().get(key);
// 2. 如果redis有,直接返回 如果redis没有,在mysql上查询
if (customer == null) {
// 3.对于高QPS的优化,进来就先加锁,保证一个请求操作,让外面的redis等待一下,避免击穿mysql(大公司的操作 )
synchronized (CustomerService.class) {
// 3.1 第二次查询redis,加锁后
customer = (Customer) redisTemplate.opsForValue().get(key);
// 4.mysql有,redis无
if (customer == null) {
// 5.再去查询我们的mysql
customer = customerMapper.selectByPrimaryKey(customerId);
if (customer == null) {
// 6.1 defaultNull 规定为redis查询为空、MySQL查询也没有,缓存一个defaultNull标识为空,以防缓存穿透
redisTemplate.opsForValue().set(key, "defaultNull", 7L, TimeUnit.DAYS);
} else {
// 6.2 把mysql查询到的数据会写到到redis, 保持双写一致性 7天过期
redisTemplate.opsForValue().set(key, customer, 7L, TimeUnit.DAYS);
}
}
}
}
return customer;
}
/**
* 业务逻辑没有写错,对于QPS <= 1000 可以使用
* @param customerId
* @return
*/
// public Customer findeCustomerById(Integer customerId) {
// Customer customer = null;
// // 缓存redis的key名称
// String key = CACHE_KEY_CUSTOMER + customerId;
// // 1.去redis上查询
// customer = (Customer) redisTemplate.opsForValue().get(key);
// // 2. 如果redis有,直接返回 如果redis没有,在mysql上查询
// if(customer == null) {
// customer = customerMapper.selectByPrimaryKey(customerId);
// if (customer != null) {
// redisTemplate.opsForValue().set(key, customer);
// }
// }
// return customer;
// }
/**
* 布隆过滤器 + 双检加锁 注意单个服务,在分布式系统锁将锁不住
*
* @param customerId
* @return
*/
public Customer findCustomerByIdWithBloomFilter(Integer customerId) {
Customer customer = null;
// 1.缓存redis的key名称
String key = CACHE_KEY_CUSTOMER + customerId;
if (!checkUtils.checkWithBloomFilter("whitelistCustomer", key)) {
log.info("白名单没有此信息,不可以访问" + key);
return null;
}
// 1.1 去redis上查询
customer = (Customer) redisTemplate.opsForValue().get(key);
// 2. 如果redis有,直接返回 如果redis没有,在mysql上查询
if (customer == null) {
// 3.对于高QPS的优化,进来就先加锁,保证一个请求操作,让外面的redis等待一下,避免击穿mysql(大公司的操作 )
synchronized (CustomerService.class) {
// 3.1 第二次查询redis,加锁后
customer = (Customer) redisTemplate.opsForValue().get(key);
// 4.mysql有,redis无
if (customer == null) {
// 5.再去查询我们的mysql
customer = customerMapper.selectByPrimaryKey(customerId);
if (customer == null) {
// 6.1 defaultNull 规定为redis查询为空、MySQL查询也没有,缓存一个defaultNull标识为空,以防缓存穿透
redisTemplate.opsForValue().set(key, "defaultNull", 7L, TimeUnit.DAYS);
} else {
// 6.2 把mysql查询到的数据会写到到redis, 保持双写一致性 7天过期
redisTemplate.opsForValue().set(key, customer, 7L, TimeUnit.DAYS);
}
}
}
}
return customer;
}
}
import com.xfcy.entities.Customer;
import com.xfcy.service.CustomerService;
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.sql.Date;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Random;
@Api("客户Customer接口+布隆过滤器讲解")
@RestController
@Slf4j
public class CustomerController {
@Resource
private CustomerService customerService;
@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("12345678910");
customer.setSex((byte) new Random().nextInt(2));
customer.setBirth(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()));
customerService.addCustomer(customer);
}
}
@ApiOperation("单个customer查询操作,按照customerId查询")
@RequestMapping(value = "/customer/{customerId}", method = RequestMethod.GET)
public Customer findCustomerById(@PathVariable("customerId") Integer customerId){
return customerService.findCustomerById(customerId);
}
@ApiOperation("布隆过滤器单个customer查询操作,按照customerId查询")
@RequestMapping(value = "/bloomfilter/{customerId}", method = RequestMethod.GET)
public Customer findCustomerByIdWithBloomFilter(@PathVariable("customerId") Integer customerId){
return customerService.findCustomerByIdWithBloomFilter(customerId);
}
}
优点
缺点
为了解决布隆过滤器不能删除元素的问题,布谷鸟过滤器横空出世。