小厂方法,传统 mysql 方式
CREATE TABLE user_sign
(
keyid BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
user_key VARCHAR(200),#京东用户ID
sign_date DATETIME,#签到日期(20210618)
sign_count INT #连续签到天数
)
INSERT INTO user_sign(user_key,sign_date,sign_count)
VALUES ('20210618-xxxx-xxxx-xxxx-xxxxxxxxxxxx','2020-06-18 15:11:12',1);
SELECT
sign_count
FROM
user_sign
WHERE
user_key = '20210618-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
AND sign_date BETWEEN '2020-06-17 00:00:00' AND '2020-06-18 23:59:59'
ORDER BY
sign_date DESC
LIMIT 1;
签到量用户小这个可以,如何解决这个点
一条签到记录对应一条记录,会占据越来越大的空间。
一个月最多31天,刚好我们的int类型是32位,那这样一个int类型就可以搞定一个月,32位大于31天,当天来了位是1没来就是0。
一条数据直接存储一个月的签到记录,不再是存储一天的签到记录。
大厂方法
基于redis的 Bitmap 实现签到日历
在签到统计时,每个用户一天的签到用1个bit位就能表示,
一个月(假设是31天)的签到情况用31个bit位就可以,一年的签到也只需要用365个bit位,根本不用太复杂的集合类型
SETBIT key offset value // 将第offset的值设为value value只能是0或1 offset 从0开始
GETBIT key offset // 获得第offset位的值
STRLEN key // 得出占多少字节 超过8位后自己按照8位一组一byte再扩容
BITCOUNT key // 得出该key里面含有几个1
BITOP and destKey key1 key2 // 对一个或多个 key 求逻辑并,并将结果保存到 destkey
BITOP or destKey key1 key2 // 对一个或多个 key 求逻辑或,并将结果保存到 destkey
BITOP XOR destKey key1 key2 // 对一个或多个 key 求逻辑异或,并将结果保存到 destkey
BITOP NOT destKey key1 key2 // 对一个或多个 key 求逻辑非,并将结果保存到 destkey
由一个初值都为零的bit数组和多个哈希函数构成,用来快速判断集合中是否存在某个元素
布隆过滤器(Bloom Filter) 是一种专门用来解决去重问题的高级数据结构。
实质就是一个大型位数组和几个不同的无偏hash函数(无偏表示分布均匀)。由一个初值为零地bit数组和多个哈希函数构成,用来快速判断某个数据是否存在。但是跟HyperLogLog一样,他也有一点不精确,存在一定的误判概率
添加 key 时
查询 key 时
结论
hash 冲突导致数据不精准1
hash 冲突导致数据不精准2
添加数据,为了尽量地址不冲突,使用多个hash函数对key进行运算,算得一个下标索引值,然后对数据长度进行取模运算得到一个位置,每个 hash 函数都会算得一个不同的位置。再把位数组的这几个位置都置为 1 就完成了 add 操作。
对字符串进行多次hash(key) → 取模运行→ 得到坑位
向布隆过滤器查询某个key是否存在时,先把这个 key 通过相同的多个 hash 函数进行运算,查看对应的位置是否都为 1,只要有一个位为零,那么说明布隆过滤器中这个 key 不存在;如果这几个位置全都是 1,那么说明极有可能存在;
使用Mapper4自动生成
先创建 mybatis-generator 工程
建表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
新建 config.properties
#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
新建 generatorConfig.xml
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
新建工程
POM
<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>
YML
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);
}
}
布隆过滤器
filter 包 BloomFilterInit
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;
/**
* @author 晓风残月Lx
* @date 2023/3/29 17:05
* 布隆过滤器白名单初始化工具类,一开始就设置一部分数据为白名单所有
* 白名单业务默认规定:布隆过滤器有,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);
}
}
utils包 CheckUtils
import javax.annotation.Resource;
/**
* @author 晓风残月Lx
* @date 2023/3/29 17:21
*/
@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;
/**
* @author 晓风残月Lx
* @date 2023/3/29 15:48
*/
@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;
}
}
controller
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;
/**
* @author 晓风残月Lx
* @date 2023/3/29 15:48
*/
@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);
}
}
启动 swagger测试,注意要看控制台
优点
缺点
为了解决布隆过滤器不能删除元素的问题,布谷鸟过滤器横空出世。