Redis与缓存设计
学习目标
- 掌握Redis数据类型和使用场景
- 理解缓存三大问题及解决方案
- 掌握Redis持久化机制
- 理解分布式锁的实现
- 掌握Redis集群和高可用方案
- 能够在面试中清晰描述Redis相关项目经验
知识结构导图
#mermaid-svg-YKBZtYSLhPVJO6MQ{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-YKBZtYSLhPVJO6MQ .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-YKBZtYSLhPVJO6MQ .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-YKBZtYSLhPVJO6MQ .error-icon{fill:#552222;}#mermaid-svg-YKBZtYSLhPVJO6MQ .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-YKBZtYSLhPVJO6MQ .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-YKBZtYSLhPVJO6MQ .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-YKBZtYSLhPVJO6MQ .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-YKBZtYSLhPVJO6MQ .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-YKBZtYSLhPVJO6MQ .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-YKBZtYSLhPVJO6MQ .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-YKBZtYSLhPVJO6MQ .marker{fill:#333333;stroke:#333333;}#mermaid-svg-YKBZtYSLhPVJO6MQ .marker.cross{stroke:#333333;}#mermaid-svg-YKBZtYSLhPVJO6MQ svg{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-YKBZtYSLhPVJO6MQ p{margin:0;}#mermaid-svg-YKBZtYSLhPVJO6MQ .edge{stroke-width:3;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section–1 rect,#mermaid-svg-YKBZtYSLhPVJO6MQ .section–1 path,#mermaid-svg-YKBZtYSLhPVJO6MQ .section–1 circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .section–1 polygon,#mermaid-svg-YKBZtYSLhPVJO6MQ .section–1 path{fill:hsl(240, 100%, 76.2745098039%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .section–1 text{fill:#ffffff;}#mermaid-svg-YKBZtYSLhPVJO6MQ .node-icon–1{font-size:40px;color:#ffffff;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-edge–1{stroke:hsl(240, 100%, 76.2745098039%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .edge-depth–1{stroke-width:17;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section–1 line{stroke:hsl(60, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled,#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled text{fill:lightgray;}#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled text{fill:#efefef;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-0 rect,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-0 path,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-0 circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-0 polygon,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-0 path{fill:hsl(60, 100%, 73.5294117647%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-0 text{fill:black;}#mermaid-svg-YKBZtYSLhPVJO6MQ .node-icon-0{font-size:40px;color:black;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-edge-0{stroke:hsl(60, 100%, 73.5294117647%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .edge-depth-0{stroke-width:14;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-0 line{stroke:hsl(240, 100%, 83.5294117647%);stroke-width:3;}#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled,#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled text{fill:lightgray;}#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled text{fill:#efefef;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-1 rect,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-1 path,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-1 circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-1 polygon,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-1 path{fill:hsl(80, 100%, 76.2745098039%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-1 text{fill:black;}#mermaid-svg-YKBZtYSLhPVJO6MQ .node-icon-1{font-size:40px;color:black;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-edge-1{stroke:hsl(80, 100%, 76.2745098039%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .edge-depth-1{stroke-width:11;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-1 line{stroke:hsl(260, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled,#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled text{fill:lightgray;}#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled text{fill:#efefef;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-2 rect,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-2 path,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-2 circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-2 polygon,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-2 path{fill:hsl(270, 100%, 76.2745098039%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-2 text{fill:#ffffff;}#mermaid-svg-YKBZtYSLhPVJO6MQ .node-icon-2{font-size:40px;color:#ffffff;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-edge-2{stroke:hsl(270, 100%, 76.2745098039%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .edge-depth-2{stroke-width:8;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-2 line{stroke:hsl(90, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled,#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled text{fill:lightgray;}#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled text{fill:#efefef;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-3 rect,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-3 path,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-3 circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-3 polygon,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-3 path{fill:hsl(300, 100%, 76.2745098039%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-3 text{fill:black;}#mermaid-svg-YKBZtYSLhPVJO6MQ .node-icon-3{font-size:40px;color:black;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-edge-3{stroke:hsl(300, 100%, 76.2745098039%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .edge-depth-3{stroke-width:5;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-3 line{stroke:hsl(120, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled,#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled text{fill:lightgray;}#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled text{fill:#efefef;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-4 rect,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-4 path,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-4 circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-4 polygon,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-4 path{fill:hsl(330, 100%, 76.2745098039%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-4 text{fill:black;}#mermaid-svg-YKBZtYSLhPVJO6MQ .node-icon-4{font-size:40px;color:black;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-edge-4{stroke:hsl(330, 100%, 76.2745098039%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .edge-depth-4{stroke-width:2;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-4 line{stroke:hsl(150, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled,#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled text{fill:lightgray;}#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled text{fill:#efefef;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-5 rect,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-5 path,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-5 circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-5 polygon,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-5 path{fill:hsl(0, 100%, 76.2745098039%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-5 text{fill:black;}#mermaid-svg-YKBZtYSLhPVJO6MQ .node-icon-5{font-size:40px;color:black;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-edge-5{stroke:hsl(0, 100%, 76.2745098039%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .edge-depth-5{stroke-width:-1;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-5 line{stroke:hsl(180, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled,#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled text{fill:lightgray;}#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled text{fill:#efefef;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-6 rect,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-6 path,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-6 circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-6 polygon,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-6 path{fill:hsl(30, 100%, 76.2745098039%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-6 text{fill:black;}#mermaid-svg-YKBZtYSLhPVJO6MQ .node-icon-6{font-size:40px;color:black;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-edge-6{stroke:hsl(30, 100%, 76.2745098039%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .edge-depth-6{stroke-width:-4;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-6 line{stroke:hsl(210, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled,#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled text{fill:lightgray;}#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled text{fill:#efefef;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-7 rect,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-7 path,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-7 circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-7 polygon,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-7 path{fill:hsl(90, 100%, 76.2745098039%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-7 text{fill:black;}#mermaid-svg-YKBZtYSLhPVJO6MQ .node-icon-7{font-size:40px;color:black;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-edge-7{stroke:hsl(90, 100%, 76.2745098039%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .edge-depth-7{stroke-width:-7;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-7 line{stroke:hsl(270, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled,#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled text{fill:lightgray;}#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled text{fill:#efefef;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-8 rect,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-8 path,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-8 circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-8 polygon,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-8 path{fill:hsl(150, 100%, 76.2745098039%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-8 text{fill:black;}#mermaid-svg-YKBZtYSLhPVJO6MQ .node-icon-8{font-size:40px;color:black;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-edge-8{stroke:hsl(150, 100%, 76.2745098039%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .edge-depth-8{stroke-width:-10;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-8 line{stroke:hsl(330, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled,#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled text{fill:lightgray;}#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled text{fill:#efefef;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-9 rect,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-9 path,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-9 circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-9 polygon,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-9 path{fill:hsl(180, 100%, 76.2745098039%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-9 text{fill:black;}#mermaid-svg-YKBZtYSLhPVJO6MQ .node-icon-9{font-size:40px;color:black;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-edge-9{stroke:hsl(180, 100%, 76.2745098039%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .edge-depth-9{stroke-width:-13;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-9 line{stroke:hsl(0, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled,#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled text{fill:lightgray;}#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled text{fill:#efefef;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-10 rect,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-10 path,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-10 circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-10 polygon,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-10 path{fill:hsl(210, 100%, 76.2745098039%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-10 text{fill:black;}#mermaid-svg-YKBZtYSLhPVJO6MQ .node-icon-10{font-size:40px;color:black;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-edge-10{stroke:hsl(210, 100%, 76.2745098039%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .edge-depth-10{stroke-width:-16;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-10 line{stroke:hsl(30, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled,#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled text{fill:lightgray;}#mermaid-svg-YKBZtYSLhPVJO6MQ .disabled text{fill:#efefef;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-root rect,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-root path,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-root circle,#mermaid-svg-YKBZtYSLhPVJO6MQ .section-root polygon{fill:hsl(240, 100%, 46.2745098039%);}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-root text{fill:#ffffff;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-root span{color:#ffffff;}#mermaid-svg-YKBZtYSLhPVJO6MQ .section-2 span{color:#ffffff;}#mermaid-svg-YKBZtYSLhPVJO6MQ .icon-container{height:100%;display:flex;justify-content:center;align-items:center;}#mermaid-svg-YKBZtYSLhPVJO6MQ .edge{fill:none;}#mermaid-svg-YKBZtYSLhPVJO6MQ .mindmap-node-label{dy:1em;alignment-baseline:middle;text-anchor:middle;dominant-baseline:middle;text-align:center;}#mermaid-svg-YKBZtYSLhPVJO6MQ :root{–mermaid-font-family:\”trebuchet ms\”,verdana,arial,sans-serif;}
Redis
数据类型
String
Hash
List
Set
ZSet
特殊类型
缓存问题
缓存穿透
缓存击穿
缓存雪崩
缓存一致性
持久化
RDB
AOF
混合持久化
高可用
主从复制
哨兵模式
集群模式
分布式锁
SETNX
Redisson
RedLock
性能优化
内存优化
慢查询
Pipeline
事务
一、Redis基础
1.1 Redis数据类型?(高频必考)
项目场景引入: 在电商系统中,需要缓存商品信息、用户会话、购物车、排行榜等数据。不同的数据使用不同的Redis数据类型。
总: Redis有5种基本类型和3种特殊类型。
分:
5种基本类型:
1. String(字符串):
特点:
– 最基本的数据类型
– 二进制安全,可以存储任何数据
– 最大512MB
使用场景:
– 缓存对象(JSON字符串)
– 计数器(INCR/DECR)
– 分布式锁(SETNX)
– 限流(INCR + EXPIRE)
– Session共享
常用命令:
SET key value [EX seconds] [NX] — 设置值
GET key — 获取值
INCR key — 自增1
DECR key — 自减1
INCRBY key increment — 自增指定值
APPEND key value — 追加字符串
STRLEN key — 获取长度
SETEX key seconds value — 设置值和过期时间
SETNX key value — 不存在时设置
示例:
// 缓存用户信息
String userJson = JSON.toJSONString(user);
redisTemplate.opsForValue().set("user:" + userId, userJson, 1, TimeUnit.HOURS);
// 计数器
redisTemplate.opsForValue().increment("page:view:" + pageId);
// 分布式锁
Boolean success = redisTemplate.opsForValue()
.setIfAbsent("lock:order:" + orderId, "1", 10, TimeUnit.SECONDS);
2. Hash(哈希表):
特点:
– 键值对集合
– 适合存储对象
– 节省内存
使用场景:
– 存储对象(用户信息、商品信息)
– 购物车(用户ID为key,商品ID为field)
– 配置信息
常用命令:
HSET key field value — 设置字段
HGET key field — 获取字段
HMSET key field1 value1 field2 value2 — 批量设置
HMGET key field1 field2 — 批量获取
HGETALL key — 获取所有字段
HDEL key field — 删除字段
HEXISTS key field — 判断字段是否存在
HLEN key — 获取字段数量
HINCRBY key field increment — 字段自增
示例:
// 存储用户信息
Map<String, String> userMap = new HashMap<>();
userMap.put("name", "张三");
userMap.put("age", "20");
userMap.put("email", "zhangsan@example.com");
redisTemplate.opsForHash().putAll("user:" + userId, userMap);
// 购物车
redisTemplate.opsForHash().put("cart:" + userId, productId, quantity);
// 获取用户信息
String name = (String) redisTemplate.opsForHash().get("user:" + userId, "name");
3. List(列表):
特点:
– 有序列表
– 可以从两端操作
– 支持阻塞操作
使用场景:
– 消息队列(LPUSH + BRPOP)
– 时间线(微博、朋友圈)
– 最新列表(最新文章、最新评论)
– 栈(LPUSH + LPOP)
常用命令:
LPUSH key value1 value2 — 左侧插入
RPUSH key value1 value2 — 右侧插入
LPOP key — 左侧弹出
RPOP key — 右侧弹出
LRANGE key start stop — 获取范围
LLEN key — 获取长度
LINDEX key index — 获取指定位置
LSET key index value — 设置指定位置
LTRIM key start stop — 保留范围
BLPOP key timeout — 阻塞左侧弹出
BRPOP key timeout — 阻塞右侧弹出
示例:
// 消息队列
redisTemplate.opsForList().leftPush("queue:order", orderJson);
String orderJson = redisTemplate.opsForList().rightPop("queue:order");
// 时间线(最新10条)
redisTemplate.opsForList().leftPush("timeline:" + userId, postJson);
List<String> posts = redisTemplate.opsForList().range("timeline:" + userId, 0, 9);
// 限制列表长度
redisTemplate.opsForList().trim("timeline:" + userId, 0, 99); // 只保留100条
4. Set(集合):
特点:
– 无序集合
– 元素唯一
– 支持集合运算
使用场景:
– 标签(用户标签、文章标签)
– 共同好友(交集)
– 推荐系统(差集)
– 去重(唯一性)
– 抽奖(随机元素)
常用命令:
SADD key member1 member2 — 添加元素
SREM key member — 删除元素
SMEMBERS key — 获取所有元素
SISMEMBER key member — 判断是否存在
SCARD key — 获取元素数量
SRANDMEMBER key count — 随机获取元素
SPOP key count — 随机弹出元素
SINTER key1 key2 — 交集
SUNION key1 key2 — 并集
SDIFF key1 key2 — 差集
示例:
// 用户标签
redisTemplate.opsForSet().add("user:tags:" + userId, "Java", "Redis", "MySQL");
// 共同好友
Set<String> commonFriends = redisTemplate.opsForSet()
.intersect("user:friends:" + userId1, "user:friends:" + userId2);
// 抽奖(随机抽取3个用户)
List<String> winners = redisTemplate.opsForSet()
.randomMembers("lottery:users", 3);
5. ZSet(有序集合):
特点:
– 有序集合
– 元素唯一
– 每个元素关联一个分数(score)
– 按分数排序
使用场景:
– 排行榜(游戏排行、销量排行)
– 延时队列(分数为时间戳)
– 优先级队列
– 范围查询(按分数范围)
常用命令:
ZADD key score member — 添加元素
ZREM key member — 删除元素
ZSCORE key member — 获取分数
ZINCRBY key increment member — 增加分数
ZRANGE key start stop [WITHSCORES] — 按分数升序
ZREVRANGE key start stop [WITHSCORES] — 按分数降序
ZRANGEBYSCORE key min max — 按分数范围
ZRANK key member — 获取排名(升序)
ZREVRANK key member — 获取排名(降序)
ZCARD key — 获取元素数量
ZCOUNT key min max — 统计分数范围内元素数量
示例:
// 排行榜
redisTemplate.opsForZSet().add("rank:sales", productId, sales);
// 获取销量前10的商品
Set<String> top10 = redisTemplate.opsForZSet()
.reverseRange("rank:sales", 0, 9);
// 获取商品排名
Long rank = redisTemplate.opsForZSet()
.reverseRank("rank:sales", productId);
// 延时队列(分数为执行时间)
long executeTime = System.currentTimeMillis() + 60000; // 1分钟后执行
redisTemplate.opsForZSet().add("delay:queue", taskJson, executeTime);
// 获取到期的任务
Set<String> tasks = redisTemplate.opsForZSet()
.rangeByScore("delay:queue", 0, System.currentTimeMillis());
3种特殊类型:
1. Bitmap(位图):
特点:
– 位数组
– 节省内存
– 支持位运算
使用场景:
– 签到统计(每天一位)
– 在线状态(用户ID为偏移量)
– 布隆过滤器
常用命令:
SETBIT key offset value — 设置位
GETBIT key offset — 获取位
BITCOUNT key [start end] — 统计1的数量
BITOP operation destkey key1 key2 — 位运算
示例:
// 用户签到(用户ID为1000,第10天签到)
redisTemplate.opsForValue().setBit("sign:202401", 1000 * 31 + 10, true);
// 统计签到天数
Long signDays = redisTemplate.execute((RedisCallback<Long>) connection -> {
return connection.bitCount("sign:202401".getBytes(), 1000 * 31, 1000 * 31 + 30);
});
2. HyperLogLog(基数统计):
特点:
– 统计唯一元素数量
– 占用内存固定(12KB)
– 有误差(0.81%)
使用场景:
– UV统计(独立访客)
– 去重计数
常用命令:
PFADD key element1 element2 — 添加元素
PFCOUNT key — 统计数量
PFMERGE destkey key1 key2 — 合并
示例:
// UV统计
redisTemplate.opsForHyperLogLog().add("uv:20240101", userId);
Long uv = redisTemplate.opsForHyperLogLog().size("uv:20240101");
3. Geo(地理位置):
特点:
– 存储地理位置
– 支持距离计算
– 支持范围查询
使用场景:
– 附近的人
– 附近的商家
– 打卡签到
常用命令:
GEOADD key longitude latitude member — 添加位置
GEOPOS key member — 获取位置
GEODIST key member1 member2 [unit] — 计算距离
GEORADIUS key longitude latitude radius [unit] — 范围查询
示例:
// 添加商家位置
redisTemplate.opsForGeo().add("shops",
new Point(116.404, 39.915), "shop1");
// 查询附近5公里的商家
Circle circle = new Circle(new Point(116.404, 39.915),
new Distance(5, Metrics.KILOMETERS));
GeoResults<RedisGeoCommands.GeoLocation<String>> results =
redisTemplate.opsForGeo().radius("shops", circle);
数据类型选择建议:
场景 推荐类型 原因
────────────────────────────────────────────────────────
缓存对象 String/Hash 简单高效
计数器 String 支持原子操作
购物车 Hash 结构清晰
消息队列 List FIFO
时间线 List 有序
标签 Set 去重
共同好友 Set 集合运算
排行榜 ZSet 有序
延时队列 ZSet 按时间排序
签到统计 Bitmap 节省内存
UV统计 HyperLogLog 节省内存
附近的人 Geo 地理位置
总: 根据业务场景选择合适的数据类型,提高性能和节省内存。
1.2 Redis为什么快?(高频)
项目场景: 在电商系统中,Redis的QPS可以达到10万+,而MySQL只有几千。为什么Redis这么快?
总: Redis快的原因是内存存储、单线程、IO多路复用、高效数据结构。
分:
1. 内存存储:
特点:
– 数据存在内存,读写快
– 避免磁盘IO
– 内存访问速度:纳秒级
– 磁盘访问速度:毫秒级
对比:
操作 内存 磁盘
读取1MB 0.25ms 20ms
随机读取 0.1μs 10ms
结论:
内存比磁盘快10万倍
2. 单线程模型:
特点:
– 避免线程切换开销
– 避免锁竞争
– 简化实现
– 保证原子性
为什么单线程还这么快?
– CPU不是瓶颈,内存和网络才是
– 单线程避免了上下文切换
– 单线程避免了锁竞争
Redis 6.0引入多线程:
– 只用于网络IO
– 命令执行还是单线程
– 提高网络IO性能
3. IO多路复用:
原理:
– 一个线程处理多个连接
– 使用epoll/select/kqueue
– 事件驱动模型
流程:
┌──────┐
│Client1│ ──┐
└──────┘ │
┌──────┐ │ ┌──────┐ ┌──────┐
│Client2│ ──┼───→│ epoll│───→│ Redis│
└──────┘ │ └──────┘ └──────┘
┌──────┐ │
│Client3│ ──┘
└──────┘
优势:
– 高并发
– 低延迟
– 资源利用率高
4. 高效数据结构:
a. SDS(Simple Dynamic String):
– 动态字符串
– O(1)获取长度
– 二进制安全
– 减少内存分配
b. 跳表(Skip List):
– ZSet底层实现
– 查询:O(log n)
– 插入:O(log n)
– 范围查询高效
c. 压缩列表(ZipList):
– 节省内存
– 连续内存
– 适合小数据量
d. 整数集合(IntSet):
– Set底层实现
– 节省内存
– 有序存储
e. 哈希表(Dict):
– Hash底层实现
– 查询:O(1)
– 渐进式rehash
5. 优化的网络模型:
特点:
– 非阻塞IO
– 事件驱动
– Reactor模式
6. 简单的协议:
RESP协议:
– 简单易解析
– 减少CPU开销
– 支持Pipeline
7. 单机性能优化:
– 避免大key
– 使用Pipeline
– 使用批量操作
– 合理设置过期时间
性能数据:
Redis性能指标:
– QPS:10万+(单机)
– 延迟:<1ms(P99)
– 内存:最大512GB
– 连接数:10000+
对比MySQL:
– QPS:几千
– 延迟:10-100ms
– 磁盘IO:瓶颈
结论:
Redis比MySQL快100-1000倍
总: 内存+单线程+IO多路复用+高效数据结构保证Redis高性能。
二、缓存问题
2.1 缓存穿透?(高频必考)
项目场景: 在电商系统中,恶意用户查询不存在的商品ID(如-1),导致每次请求都打到数据库,数据库压力激增。
总: 缓存穿透是查询不存在的数据,导致请求打到数据库。
分:
问题描述:
流程:
用户请求 → 查询缓存(无) → 查询数据库(无) → 返回空
影响:
– 缓存失效
– 数据库压力大
– 可能被恶意攻击
示例:
// 查询商品
public Product getProduct(Long productId) {
// 1. 查询缓存
Product product = redisTemplate.opsForValue().get("product:" + productId);
if (product != null) {
return product;
}
// 2. 查询数据库
product = productMapper.selectById(productId);
if (product == null) {
// 数据不存在,但每次都查数据库
return null;
}
// 3. 写入缓存
redisTemplate.opsForValue().set("product:" + productId, product, 1, TimeUnit.HOURS);
return product;
}
解决方案:
1. 布隆过滤器(推荐):
原理:
– 判断数据是否存在
– 存在误判(可能存在但实际不存在)
– 不会漏判(说不存在就一定不存在)
实现:
// 初始化布隆过滤器
BloomFilter<Long> bloomFilter = BloomFilter.create(
Funnels.longFunnel(),
10000000, // 预计元素数量
0.01 // 误判率
);
// 将所有商品ID加入布隆过滤器
List<Product> products = productMapper.selectAll();
for (Product product : products) {
bloomFilter.put(product.getId());
}
// 查询商品
public Product getProduct(Long productId) {
// 1. 布隆过滤器判断
if (!bloomFilter.mightContain(productId)) {
return null; // 一定不存在,直接返回
}
// 2. 查询缓存
Product product = redisTemplate.opsForValue().get("product:" + productId);
if (product != null) {
return product;
}
// 3. 查询数据库
product = productMapper.selectById(productId);
if (product != null) {
redisTemplate.opsForValue().set("product:" + productId, product, 1, TimeUnit.HOURS);
}
return product;
}
优点:
– 内存占用小(10亿数据只需1.2GB)
– 查询速度快(O(k),k为哈希函数数量)
– 有效拦截不存在的请求
缺点:
– 有误判率
– 不支持删除(可以使用Counting Bloom Filter)
2. 缓存空值:
实现:
public Product getProduct(Long productId) {
// 1. 查询缓存
String cacheKey = "product:" + productId;
Product product = redisTemplate.opsForValue().get(cacheKey);
// 2. 缓存命中
if (product != null) {
// 判断是否为空对象
if (product.getId() == null) {
return null; // 空对象,返回null
}
return product;
}
// 3. 查询数据库
product = productMapper.selectById(productId);
if (product == null) {
// 4. 缓存空对象(设置较短过期时间)
Product emptyProduct = new Product();
redisTemplate.opsForValue().set(cacheKey, emptyProduct, 5, TimeUnit.MINUTES);
return null;
}
// 5. 缓存正常对象
redisTemplate.opsForValue().set(cacheKey, product, 1, TimeUnit.HOURS);
return product;
}
优点:
– 实现简单
– 有效防止穿透
缺点:
– 占用缓存空间
– 可能缓存大量空值
优化:
– 设置较短过期时间(5分钟)
– 使用特殊标记(如空字符串)
3. 参数校验:
实现:
@GetMapping("/product/{id}")
public Result<Product> getProduct(@PathVariable Long id) {
// 1. 参数校验
if (id == null || id <= 0) {
return Result.error("商品ID不合法");
}
// 2. 查询商品
Product product = productService.getProduct(id);
return Result.success(product);
}
优点:
– 拦截非法请求
– 减轻后端压力
缺点:
– 无法防止合法但不存在的ID
4. 限流:
实现:
@GetMapping("/product/{id}")
@RateLimiter(limit = 100, window = 1) // 每秒最多100次
public Result<Product> getProduct(@PathVariable Long id) {
Product product = productService.getProduct(id);
return Result.success(product);
}
优点:
– 防止恶意攻击
– 保护系统
缺点:
– 可能影响正常用户
对比方案:
方案 优点 缺点 适用场景
────────────────────────────────────────────────────────────────────
布隆过滤器 内存小,速度快 有误判,不支持删除 数据量大
缓存空值 实现简单 占用空间 数据量小
参数校验 拦截非法请求 无法防止合法ID 通用
限流 防止攻击 影响正常用户 高并发
推荐方案:
布隆过滤器 + 缓存空值 + 参数校验 + 限流
总: 使用布隆过滤器或缓存空值解决穿透,推荐布隆过滤器。
2.2 缓存击穿?(高频必考)
项目场景: 在电商系统中,热门商品的缓存过期,瞬间大量请求打到数据库,导致数据库压力激增。
总: 缓存击穿是热点数据过期,大量请求打到数据库。
分:
问题描述:
流程:
热点key过期 → 大量并发请求 → 都查数据库 → 数据库压力大
示例:
// 秒杀商品缓存过期
时间 请求数 缓存 数据库查询
10:00 1000 命中 0
10:01 1000 过期 1000 ← 击穿
10:02 1000 命中 0
影响:
– 数据库压力激增
– 响应时间变长
– 可能导致雪崩
解决方案:
1. 互斥锁(推荐):
实现:
public Product getProduct(Long productId) {
String cacheKey = "product:" + productId;
String lockKey = "lock:product:" + productId;
// 1. 查询缓存
Product product = redisTemplate.opsForValue().get(cacheKey);
if (product != null) {
return product;
}
// 2. 获取锁
Boolean locked = redisTemplate.opsForValue()
.setIfAbsent(lockKey, "1", 10, TimeUnit.SECONDS);
if (locked) {
try {
// 3. 双重检查
product = redisTemplate.opsForValue().get(cacheKey);
if (product != null) {
return product;
}
// 4. 查询数据库
product = productMapper.selectById(productId);
// 5. 写入缓存
if (product != null) {
redisTemplate.opsForValue().set(cacheKey, product, 1, TimeUnit.HOURS);
}
return product;
} finally {
// 6. 释放锁
redisTemplate.delete(lockKey);
}
} else {
// 7. 未获取到锁,等待后重试
try {
Thread.sleep(50);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return getProduct(productId); // 递归重试
}
}
优点:
– 只有一个请求查数据库
– 其他请求等待
– 保护数据库
缺点:
– 等待时间长
– 可能超时
优化:
– 使用Redisson分布式锁
– 设置合理的超时时间
– 使用自旋等待
2. 热点数据永不过期:
方案1:设置过期时间为-1
redisTemplate.opsForValue().set(cacheKey, product); // 不设置过期时间
方案2:逻辑过期
public class CacheData {
private Object data;
private Long expireTime; // 逻辑过期时间
}
public Product getProduct(Long productId) {
String cacheKey = "product:" + productId;
// 1. 查询缓存
CacheData cacheData = redisTemplate.opsForValue().get(cacheKey);
if (cacheData == null) {
// 缓存不存在,查询数据库
Product product = productMapper.selectById(productId);
cacheData = new CacheData();
cacheData.setData(product);
cacheData.setExpireTime(System.currentTimeMillis() + 3600000);
redisTemplate.opsForValue().set(cacheKey, cacheData);
return product;
}
// 2. 判断逻辑过期
if (cacheData.getExpireTime() < System.currentTimeMillis()) {
// 3. 异步更新缓存
CompletableFuture.runAsync(() -> {
Product product = productMapper.selectById(productId);
cacheData.setData(product);
cacheData.setExpireTime(System.currentTimeMillis() + 3600000);
redisTemplate.opsForValue().set(cacheKey, cacheData);
});
}
// 4. 返回旧数据
return (Product) cacheData.getData();
}
优点:
– 不会击穿
– 性能好
缺点:
– 可能返回旧数据
– 占用内存
3. 提前更新:
实现:
@Scheduled(fixedDelay = 3000000) // 50分钟执行一次
public void refreshHotCache() {
// 1. 获取热点商品列表
List<Long> hotProductIds = getHotProductIds();
// 2. 提前更新缓存
for (Long productId : hotProductIds) {
Product product = productMapper.selectById(productId);
redisTemplate.opsForValue().set("product:" + productId, product, 1, TimeUnit.HOURS);
}
}
优点:
– 缓存始终有效
– 不会击穿
缺点:
– 需要识别热点数据
– 增加系统复杂度
4. 多级缓存:
架构:
请求 → 本地缓存(Caffeine) → Redis → 数据库
实现:
@Service
public class ProductService {
@Autowired
private RedisTemplate<String, Product> redisTemplate;
@Autowired
private ProductMapper productMapper;
// 本地缓存
private Cache<Long, Product> localCache = Caffeine.newBuilder()
.maximumSize(1000)
.expireAfterWrite(5, TimeUnit.MINUTES)
.build();
public Product getProduct(Long productId) {
// 1. 查询本地缓存
Product product = localCache.getIfPresent(productId);
if (product != null) {
return product;
}
// 2. 查询Redis
product = redisTemplate.opsForValue().get("product:" + productId);
if (product != null) {
localCache.put(productId, product);
return product;
}
// 3. 查询数据库
product = productMapper.selectById(productId);
if (product != null) {
redisTemplate.opsForValue().set("product:" + productId, product, 1, TimeUnit.HOURS);
localCache.put(productId, product);
}
return product;
}
}
优点:
– 减轻Redis压力
– 响应速度快
缺点:
– 数据一致性问题
– 内存占用
对比方案:
方案 优点 缺点 适用场景
────────────────────────────────────────────────────────────────────
互斥锁 保护数据库 等待时间长 通用
永不过期 不会击穿 占用内存 热点数据
提前更新 缓存始终有效 需要识别热点 可预测热点
多级缓存 性能好 一致性问题 高并发
推荐方案:
互斥锁 + 热点数据永不过期
总: 使用互斥锁或热点数据不过期解决击穿,推荐互斥锁。
2.3 缓存雪崩?(高频必考)
项目场景: 在电商系统中,大促期间设置了大量商品缓存,过期时间都是1小时。1小时后,所有缓存同时过期,导致数据库崩溃。
总: 缓存雪崩是大量缓存同时过期,导致数据库压力激增。
分:
问题描述:
原因:
1. 大量key同时过期
2. Redis宕机
3. 缓存预热不足
流程:
大量key同时过期 → 请求打到数据库 → 数据库崩溃 → 服务不可用
示例:
// 大促期间,设置了10万个商品缓存,过期时间都是1小时
for (Product product : products) {
redisTemplate.opsForValue().set("product:" + product.getId(),
product, 1, TimeUnit.HOURS); // 都是1小时
}
// 1小时后,所有缓存同时过期
// 大量请求打到数据库
// 数据库崩溃
影响:
– 数据库压力激增
– 服务不可用
– 用户体验差
– 可能引发连锁反应
解决方案:
1. 过期时间随机化(推荐):
实现:
public void setCache(String key, Object value, long baseTime) {
// 基础时间 + 随机时间
long randomTime = ThreadLocalRandom.current().nextLong(0, 300); // 0-5分钟
long expireTime = baseTime + randomTime;
redisTemplate.opsForValue().set(key, value, expireTime, TimeUnit.SECONDS);
}
// 使用
for (Product product : products) {
setCache("product:" + product.getId(), product, 3600); // 1小时 ± 5分钟
}
优点:
– 避免同时过期
– 实现简单
缺点:
– 过期时间不精确
2. 多级缓存:
架构:
请求 → 本地缓存(Caffeine) → Redis → 数据库
实现:
@Service
public class ProductService {
// 本地缓存
private Cache<Long, Product> localCache = Caffeine.newBuilder()
.maximumSize(10000)
.expireAfterWrite(5, TimeUnit.MINUTES)
.build();
public Product getProduct(Long productId) {
// 1. 查询本地缓存
Product product = localCache.getIfPresent(productId);
if (product != null) {
return product;
}
// 2. 查询Redis
product = redisTemplate.opsForValue().get("product:" + productId);
if (product != null) {
localCache.put(productId, product);
return product;
}
// 3. 查询数据库
product = productMapper.selectById(productId);
if (product != null) {
redisTemplate.opsForValue().set("product:" + productId, product, 1, TimeUnit.HOURS);
localCache.put(productId, product);
}
return product;
}
}
优点:
– 降低Redis压力
– 即使Redis宕机,本地缓存仍可用
缺点:
– 数据一致性问题
– 内存占用
3. 限流降级:
实现:
@Service
public class ProductService {
// 限流器(每秒最多1000次)
private RateLimiter rateLimiter = RateLimiter.create(1000);
public Product getProduct(Long productId) {
// 1. 限流
if (!rateLimiter.tryAcquire()) {
// 降级:返回默认值或错误
return getDefaultProduct();
}
// 2. 正常查询
return queryProduct(productId);
}
private Product getDefaultProduct() {
// 返回默认商品或错误提示
Product product = new Product();
product.setName("系统繁忙,请稍后再试");
return product;
}
}
优点:
– 保护数据库
– 避免雪崩
缺点:
– 影响用户体验
4. Redis集群:
架构:
┌──────┐ ┌──────┐ ┌──────┐
│Master1│ │Master2│ │Master3│
└───┬──┘ └───┬──┘ └───┬──┘
│ │ │
┌───▼──┐ ┌───▼──┐ ┌───▼──┐
│Slave1│ │Slave2│ │Slave3│
└──────┘ └──────┘ └──────┘
优点:
– 高可用
– 避免单点故障
缺点:
– 运维复杂
5. 缓存预热:
实现:
@Component
public class CacheWarmer implements ApplicationRunner {
@Autowired
private ProductService productService;
@Override
public void run(ApplicationArguments args) {
// 应用启动时预热缓存
List<Product> hotProducts = productService.getHotProducts();
for (Product product : hotProducts) {
redisTemplate.opsForValue().set("product:" + product.getId(),
product, 1, TimeUnit.HOURS);
}
}
}
优点:
– 避免冷启动
– 提高命中率
缺点:
– 启动时间长
6. 熔断降级:
实现:
@Service
public class ProductService {
@HystrixCommand(fallbackMethod = "getProductFallback")
public Product getProduct(Long productId) {
// 查询商品
return queryProduct(productId);
}
public Product getProductFallback(Long productId) {
// 降级:返回默认值
return getDefaultProduct();
}
}
优点:
– 快速失败
– 保护系统
缺点:
– 需要降级方案
对比方案:
方案 优点 缺点 适用场景
────────────────────────────────────────────────────────────────────
过期时间随机化 简单有效 过期时间不精确 通用
多级缓存 降低压力 一致性问题 高并发
限流降级 保护系统 影响体验 高并发
Redis集群 高可用 运维复杂 生产环境
缓存预热 避免冷启动 启动慢 可预测
熔断降级 快速失败 需要降级方案 高可用
推荐方案:
过期时间随机化 + 多级缓存 + 限流降级 + Redis集群
总: 过期时间随机化+多级缓存+限流降级解决雪崩。
2.4 缓存一致性?(高频)
项目场景: 在电商系统中,商品价格更新后,需要同步更新缓存。如果处理不当,会导致用户看到旧价格。
总: 缓存一致性是保证缓存和数据库数据一致。
分:
问题描述:
场景:
1. 更新数据库
2. 更新缓存
3. 如果缓存更新失败,数据不一致
解决方案:
1. Cache Aside Pattern(旁路缓存,推荐):
读操作:
1. 查询缓存
2. 缓存命中,返回
3. 缓存未命中,查询数据库
4. 写入缓存,返回
写操作:
1. 更新数据库
2. 删除缓存(而不是更新缓存)
实现:
// 读操作
public Product getProduct(Long productId) {
String cacheKey = "product:" + productId;
// 1. 查询缓存
Product product = redisTemplate.opsForValue().get(cacheKey);
if (product != null) {
return product;
}
// 2. 查询数据库
product = productMapper.selectById(productId);
// 3. 写入缓存
if (product != null) {
redisTemplate.opsForValue().set(cacheKey, product, 1, TimeUnit.HOURS);
}
return product;
}
// 写操作
@Transactional
public void updateProduct(Product product) {
// 1. 更新数据库
productMapper.updateById(product);
// 2. 删除缓存
redisTemplate.delete("product:" + product.getId());
}
为什么删除而不是更新?
– 更新缓存可能失败
– 更新缓存可能有并发问题
– 删除缓存更简单可靠
优点:
– 实现简单
– 一致性好
缺点:
– 删除缓存后,下次查询需要查数据库
2. Read/Write Through Pattern(读写穿透):
特点:
– 应用只和缓存交互
– 缓存负责和数据库交互
实现:
@Service
public class CacheService {
@Autowired
private RedisTemplate<String, Product> redisTemplate;
@Autowired
private ProductMapper productMapper;
// 读操作
public Product get(Long productId) {
String cacheKey = "product:" + productId;
// 1. 查询缓存
Product product = redisTemplate.opsForValue().get(cacheKey);
if (product != null) {
return product;
}
// 2. 缓存未命中,查询数据库
product = productMapper.selectById(productId);
// 3. 写入缓存
if (product != null) {
redisTemplate.opsForValue().set(cacheKey, product, 1, TimeUnit.HOURS);
}
return product;
}
// 写操作
@Transactional
public void update(Product product) {
// 1. 更新数据库
productMapper.updateById(product);
// 2. 更新缓存
redisTemplate.opsForValue().set("product:" + product.getId(),
product, 1, TimeUnit.HOURS);
}
}
优点:
– 应用逻辑简单
– 缓存和数据库解耦
缺点:
– 实现复杂
– 需要缓存服务
3. Write Behind Pattern(异步写回):
特点:
– 先更新缓存
– 异步更新数据库
实现:
@Service
public class CacheService {
@Autowired
private RedisTemplate<String, Product> redisTemplate;
@Autowired
private ProductMapper productMapper;
// 写操作
public void update(Product product) {
// 1. 更新缓存
redisTemplate.opsForValue().set("product:" + product.getId(),
product, 1, TimeUnit.HOURS);
// 2. 异步更新数据库
CompletableFuture.runAsync(() -> {
productMapper.updateById(product);
});
}
}
优点:
– 写入速度快
– 减轻数据库压力
缺点:
– 数据可能丢失
– 一致性差
4. 延时双删:
实现:
@Transactional
public void updateProduct(Product product) {
String cacheKey = "product:" + product.getId();
// 1. 删除缓存
redisTemplate.delete(cacheKey);
// 2. 更新数据库
productMapper.updateById(product);
// 3. 延时删除缓存
CompletableFuture.runAsync(() -> {
try {
Thread.sleep(500); // 延时500ms
redisTemplate.delete(cacheKey);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
为什么要延时双删?
– 防止并发读写导致的不一致
– 第一次删除:删除旧缓存
– 更新数据库
– 第二次删除:删除可能的脏缓存
优点:
– 一致性好
缺点:
– 实现复杂
– 延时时间难以确定
5. Canal + MQ(推荐):
架构:
MySQL → Canal监听binlog → MQ → 消费者删除缓存
实现:
@Component
public class CanalListener {
@Autowired
private RedisTemplate<String, Product> redisTemplate;
@KafkaListener(topics = "canal-product")
public void onMessage(String message) {
// 1. 解析Canal消息
CanalMessage canalMessage = JSON.parseObject(message, CanalMessage.class);
// 2. 删除缓存
if ("UPDATE".equals(canalMessage.getType())) {
Long productId = canalMessage.getData().get("id");
redisTemplate.delete("product:" + productId);
}
}
}
优点:
– 解耦
– 可靠性高
– 支持多种缓存策略
缺点:
– 实现复杂
– 需要Canal和MQ
对比方案:
方案 优点 缺点 适用场景
────────────────────────────────────────────────────────────────────
Cache Aside 简单可靠 下次查询慢 通用
Read/Write Through 逻辑简单 实现复杂 缓存服务
Write Behind 写入快 可能丢失 高性能
延时双删 一致性好 实现复杂 强一致性
Canal + MQ 解耦可靠 实现复杂 大型系统
推荐方案:
Cache Aside(中小型系统)
Canal + MQ(大型系统)
总: 推荐使用Cache Aside模式,大型系统使用Canal + MQ。
三、Redis持久化
3.1 RDB和AOF?(高频必考)
项目场景: 在电商系统中,Redis存储了用户会话、购物车等重要数据。如果Redis宕机,需要快速恢复数据。
总: RDB是快照持久化,AOF是日志持久化。
分:
RDB(Redis Database):
原理:
– 定期保存内存快照到磁盘
– 生成二进制文件(dump.rdb)
– 全量备份
触发方式:
1. 手动触发:
SAVE:阻塞Redis,直到完成
BGSAVE:后台执行,不阻塞
2. 自动触发:
配置:save 900 1 # 900秒内至少1个key变化
save 300 10 # 300秒内至少10个key变化
save 60 10000 # 60秒内至少10000个key变化
流程:
1. Redis fork子进程
2. 子进程将数据写入临时RDB文件
3. 写入完成后,替换旧的RDB文件
优点:
– 文件小,压缩存储
– 恢复速度快
– 对性能影响小(fork子进程)
– 适合备份和灾难恢复
缺点:
– 数据可能丢失(最后一次快照后的数据)
– fork子进程耗时(数据量大时)
– 不适合实时性要求高的场景
配置:
# redis.conf
save 900 1
save 300 10
save 60 10000
stop-writes-on-bgsave-error yes # BGSAVE失败时停止写入
rdbcompression yes # 压缩RDB文件
rdbchecksum yes # 校验RDB文件
dbfilename dump.rdb # RDB文件名
dir /var/lib/redis # RDB文件目录
AOF(Append Only File):
原理:
– 记录每个写命令
– 追加到AOF文件
– 增量备份
触发方式:
1. always:每个命令都同步
2. everysec:每秒同步一次(推荐)
3. no:由操作系统决定
流程:
1. 客户端发送写命令
2. Redis执行命令
3. 将命令追加到AOF缓冲区
4. 根据策略同步到磁盘
优点:
– 数据完整性好(最多丢失1秒数据)
– 文件可读,易于修复
– 支持AOF重写,压缩文件
缺点:
– 文件大
– 恢复速度慢
– 对性能影响大
配置:
# redis.conf
appendonly yes # 开启AOF
appendfilename "appendonly.aof" # AOF文件名
appendfsync everysec # 同步策略
no-appendfsync-on-rewrite no # 重写时不同步
auto-aof-rewrite-percentage 100 # 文件大小增长100%时重写
auto-aof-rewrite-min-size 64mb # 文件最小64MB时重写
AOF重写:
原理:
– 压缩AOF文件
– 合并重复命令
– 删除过期数据
示例:
# 原始AOF
SET key1 value1
SET key1 value2
SET key1 value3
DEL key2
SET key2 value4
# 重写后
SET key1 value3
SET key2 value4
触发方式:
1. 手动触发:BGREWRITEAOF
2. 自动触发:配置auto-aof-rewrite-percentage
流程:
1. Redis fork子进程
2. 子进程根据内存数据生成新AOF文件
3. 父进程继续处理命令,写入AOF缓冲区
4. 子进程完成后,父进程将缓冲区数据追加到新AOF文件
5. 替换旧的AOF文件
混合持久化(Redis 4.0+):
原理:
– RDB + AOF
– AOF重写时,先写入RDB格式,再追加增量AOF
优点:
– 结合RDB和AOF的优点
– 恢复速度快
– 数据完整性好
配置:
aof-use-rdb-preamble yes # 开启混合持久化
对比:
特性 RDB AOF 混合持久化
────────────────────────────────────────────────────────────────────
数据完整性 差(可能丢失) 好(最多丢失1秒) 好
文件大小 小 大 中
恢复速度 快 慢 快
性能影响 小 大 中
适用场景 备份、灾难恢复 实时性要求高 通用
选择建议:
1. 数据不重要(可以丢失):
– 只使用RDB
– 配置:save 900 1
2. 数据重要(不能丢失):
– 使用AOF
– 配置:appendfsync everysec
3. 数据非常重要:
– 使用RDB + AOF
– 配置:save 900 1 + appendonly yes
4. 推荐配置(生产环境):
– 使用混合持久化
– 配置:aof-use-rdb-preamble yes
实际案例:
电商系统:
– 用户会话:AOF(不能丢失)
– 商品缓存:RDB(可以重建)
– 购物车:AOF(不能丢失)
– 排行榜:RDB(可以重建)
总: 根据业务需求选择持久化方式,推荐使用混合持久化。
四、分布式锁
4.1 Redis分布式锁实现?(高频必考)
项目场景: 在秒杀系统中,多个用户同时抢购商品,需要使用分布式锁保证库存不会超卖。
总: 使用SETNX+过期时间实现分布式锁。
分:
为什么需要分布式锁?
单机锁的问题:
– synchronized只能锁单个JVM
– 多个服务器无法共享锁
– 无法解决分布式场景
分布式锁的要求:
1. 互斥性:同一时刻只有一个客户端持有锁
2. 安全性:只有持有锁的客户端才能释放锁
3. 死锁避免:即使客户端崩溃,锁也能被释放
4. 容错性:Redis宕机后,锁能正常工作
基础实现(有问题):
// ✗ 错误实现1:没有过期时间
public boolean lock(String key, String value) {
Boolean success = redisTemplate.opsForValue().setIfAbsent(key, value);
return success != null && success;
}
// 问题:如果客户端崩溃,锁永远不会释放
// ✗ 错误实现2:分两步操作
public boolean lock(String key, String value, int expireTime) {
Boolean success = redisTemplate.opsForValue().setIfAbsent(key, value);
if (success) {
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
}
return success != null && success;
}
// 问题:SETNX和EXPIRE不是原子操作,如果SETNX后崩溃,锁永远不会释放
// ✗ 错误实现3:释放锁不判断
public void unlock(String key) {
redisTemplate.delete(key);
}
// 问题:可能释放别人的锁
正确实现:
1. 加锁(SETNX + 过期时间,原子操作):
public boolean lock(String key, String value, int expireTime) {
// SET key value NX EX expireTime
Boolean success = redisTemplate.opsForValue()
.setIfAbsent(key, value, expireTime, TimeUnit.SECONDS);
return success != null && success;
}
// 使用
String lockKey = "lock:product:" + productId;
String lockValue = UUID.randomUUID().toString(); // 唯一值
boolean locked = lock(lockKey, lockValue, 10);
if (locked) {
try {
// 执行业务逻辑
deductStock(productId);
} finally {
// 释放锁
unlock(lockKey, lockValue);
}
}
2. 解锁(Lua脚本保证原子性):
public boolean unlock(String key, String value) {
// Lua脚本:判断是否是自己的锁,是才删除
String script =
"if redis.call('get', KEYS[1]) == ARGV[1] then " +
" return redis.call('del', KEYS[1]) " +
"else " +
" return 0 " +
"end";
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
redisScript.setScriptText(script);
redisScript.setResultType(Long.class);
Long result = redisTemplate.execute(redisScript,
Collections.singletonList(key), value);
return result != null && result == 1;
}
为什么使用Lua脚本?
– 保证判断和删除的原子性
– 避免删除别人的锁
完整示例:
@Service
public class ProductService {
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Autowired
private ProductMapper productMapper;
public boolean deductStock(Long productId, int quantity) {
String lockKey = "lock:product:" + productId;
String lockValue = UUID.randomUUID().toString();
// 1. 加锁
boolean locked = lock(lockKey, lockValue, 10);
if (!locked) {
return false; // 获取锁失败
}
try {
// 2. 查询库存
Product product = productMapper.selectById(productId);
if (product.getStock() < quantity) {
return false; // 库存不足
}
// 3. 扣减库存
product.setStock(product.getStock() – quantity);
productMapper.updateById(product);
return true;
} finally {
// 4. 释放锁
unlock(lockKey, lockValue);
}
}
private boolean lock(String key, String value, int expireTime) {
Boolean success = redisTemplate.opsForValue()
.setIfAbsent(key, value, expireTime, TimeUnit.SECONDS);
return success != null && success;
}
private boolean unlock(String key, String value) {
String script =
"if redis.call('get', KEYS[1]) == ARGV[1] then " +
" return redis.call('del', KEYS[1]) " +
"else " +
" return 0 " +
"end";
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
redisScript.setScriptText(script);
redisScript.setResultType(Long.class);
Long result = redisTemplate.execute(redisScript,
Collections.singletonList(key), value);
return result != null && result == 1;
}
}
问题和优化:
1. 锁过期问题:
问题:
– 业务执行时间超过锁过期时间
– 锁自动释放,其他客户端获取锁
– 导致并发问题
解决方案:
a. 延长过期时间(不推荐)
b. 锁续期(推荐)
// 锁续期
public class LockRenewer {
private ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public void startRenew(String key, String value, int expireTime) {
scheduler.scheduleAtFixedRate(() -> {
// 每隔expireTime/3续期
String script =
"if redis.call('get', KEYS[1]) == ARGV[1] then " +
" return redis.call('expire', KEYS[1], ARGV[2]) " +
"else " +
" return 0 " +
"end";
redisTemplate.execute(script,
Collections.singletonList(key), value, expireTime);
}, expireTime / 3, expireTime / 3, TimeUnit.SECONDS);
}
public void stopRenew() {
scheduler.shutdown();
}
}
2. Redis宕机问题:
问题:
– Redis宕机,锁丢失
– 多个客户端同时获取锁
解决方案:
a. Redis集群(主从+哨兵)
b. RedLock算法
3. 使用Redisson(推荐):
Redisson是Redis的Java客户端,提供了完善的分布式锁实现。
依赖:
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.17.0</version>
</dependency>
配置:
@Configuration
public class RedissonConfig {
@Bean
public RedissonClient redissonClient() {
Config config = new Config();
config.useSingleServer()
.setAddress("redis://localhost:6379")
.setPassword("password");
return Redisson.create(config);
}
}
使用:
@Service
public class ProductService {
@Autowired
private RedissonClient redissonClient;
public boolean deductStock(Long productId, int quantity) {
String lockKey = "lock:product:" + productId;
RLock lock = redissonClient.getLock(lockKey);
try {
// 尝试加锁,最多等待10秒,锁30秒后自动释放
boolean locked = lock.tryLock(10, 30, TimeUnit.SECONDS);
if (!locked) {
return false;
}
// 执行业务逻辑
// Redisson会自动续期(watchdog机制)
deductStockInternal(productId, quantity);
return true;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
} finally {
// 释放锁
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}
}
Redisson优势:
– 自动续期(watchdog机制)
– 可重入锁
– 公平锁
– 读写锁
– 信号量
– 闭锁
RedLock算法:
原理:
– 在多个独立的Redis实例上加锁
– 超过半数成功才算加锁成功
– 提高可靠性
实现:
@Service
public class ProductService {
@Autowired
private RedissonClient redissonClient1;
@Autowired
private RedissonClient redissonClient2;
@Autowired
private RedissonClient redissonClient3;
public boolean deductStock(Long productId, int quantity) {
String lockKey = "lock:product:" + productId;
RLock lock1 = redissonClient1.getLock(lockKey);
RLock lock2 = redissonClient2.getLock(lockKey);
RLock lock3 = redissonClient3.getLock(lockKey);
RedissonRedLock redLock = new RedissonRedLock(lock1, lock2, lock3);
try {
boolean locked = redLock.tryLock(10, 30, TimeUnit.SECONDS);
if (!locked) {
return false;
}
// 执行业务逻辑
deductStockInternal(productId, quantity);
return true;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
} finally {
redLock.unlock();
}
}
}
对比方案:
方案 优点 缺点 适用场景
────────────────────────────────────────────────────────────────────
SETNX+Lua 简单 需要手动续期 简单场景
Redisson 功能完善,自动续期 依赖第三方库 生产环境
RedLock 可靠性高 实现复杂 高可用场景
推荐方案:
生产环境使用Redisson
总: Redis分布式锁简单高效,生产环境推荐使用Redisson。
五、Redis集群
5.1 Redis集群方案?(高频)
项目场景: 在电商系统中,单个Redis实例无法支撑高并发,需要使用Redis集群。
总: Redis有主从复制、哨兵模式、集群模式三种方案。
分:
1. 主从复制(Master-Slave):
架构:
┌──────┐
│Master│ ← 写
└───┬──┘
│ 复制
├────────┬────────┐
↓ ↓ ↓
┌──────┐ ┌──────┐ ┌──────┐
│Slave1│ │Slave2│ │Slave3│ ← 读
└──────┘ └──────┘ └──────┘
特点:
– 一主多从
– 主节点负责写,从节点负责读
– 数据自动同步
– 读写分离
配置:
# 主节点(无需配置)
# 从节点
replicaof 主节点IP 主节点端口
masterauth 主节点密码
优点:
– 读写分离,提高性能
– 数据备份
– 高可用(从节点可以升级为主节点)
缺点:
– 主节点宕机,需要手动切换
– 写操作只能在主节点
2. 哨兵模式(Sentinel):
架构:
┌─────────┐ ┌─────────┐ ┌─────────┐
│Sentinel1│ │Sentinel2│ │Sentinel3│ ← 监控
└────┬────┘ └────┬────┘ └────┬────┘
│ │ │
└────────────┼────────────┘
↓
┌──────┐
│Master│
└───┬──┘
│
┌───────┼───────┐
↓ ↓ ↓
┌──────┐┌──────┐┌──────┐
│Slave1││Slave2││Slave3│
└──────┘└──────┘└──────┘
特点:
– 监控主从节点
– 自动故障转移
– 通知客户端
配置:
# sentinel.conf
sentinel monitor mymaster 主节点IP 主节点端口 2 # 2个哨兵同意才故障转移
sentinel auth-pass mymaster 主节点密码
sentinel down-after-milliseconds mymaster 5000 # 5秒无响应判定下线
sentinel parallel-syncs mymaster 1 # 故障转移时,同时同步的从节点数
sentinel failover-timeout mymaster 180000 # 故障转移超时时间
启动:
redis-sentinel sentinel.conf
优点:
– 自动故障转移
– 高可用
– 监控和通知
缺点:
– 写操作只能在主节点
– 无法水平扩展
3. 集群模式(Cluster):
架构:
┌──────┐ ┌──────┐ ┌──────┐
│Master1│ │Master2│ │Master3│
│0-5460 │ │5461- │ │10923- │
│ │ │10922 │ │16383 │
└───┬──┘ └───┬──┘ └───┬──┘
│ │ │
┌───▼──┐ ┌───▼──┐ ┌───▼──┐
│Slave1│ │Slave2│ │Slave3│
└──────┘ └──────┘ └──────┘
特点:
– 数据分片(16384个槽)
– 多个主节点
– 自动故障转移
– 水平扩展
配置:
# redis.conf
cluster-enabled yes
cluster-config-file nodes.conf
cluster-node-timeout 5000
创建集群:
redis-cli –cluster create \\
节点1IP:端口 节点2IP:端口 节点3IP:端口 \\
节点4IP:端口 节点5IP:端口 节点6IP:端口 \\
–cluster-replicas 1 # 每个主节点1个从节点
优点:
– 水平扩展
– 高可用
– 自动故障转移
– 支持海量数据
缺点:
– 实现复杂
– 不支持多key操作(跨槽)
– 运维复杂
对比:
方案 优点 缺点 适用场景
────────────────────────────────────────────────────────────────────
主从复制 简单 需要手动切换 小型系统
哨兵模式 自动故障转移 无法水平扩展 中型系统
集群模式 水平扩展,高可用 实现复杂 大型系统
选择建议:
– 数据量小(<10GB):主从复制
– 数据量中(10-100GB):哨兵模式
– 数据量大(>100GB):集群模式
总: 根据数据量和可用性要求选择合适的集群方案。
六、项目面试题
6.1 如何在面试中描述Redis使用经验?
面试官:说说你在项目中是如何使用Redis的?
回答模板:
"在我做的电商订单系统中,使用Redis解决了多个问题。
1. 使用场景:
a. 缓存商品信息(String):
– 热门商品缓存到Redis
– 过期时间1小时
– 命中率90%以上
– 响应时间从100ms降低到5ms
b. 购物车(Hash):
– 用户ID为key,商品ID为field
– 实时更新,性能好
– 支持快速查询和修改
c. 排行榜(ZSet):
– 销量排行榜
– 实时更新
– 支持范围查询
d. 分布式锁(String):
– 秒杀场景使用Redisson分布式锁
– 保证库存不会超卖
– 支持自动续期
2. 缓存问题解决:
a. 缓存穿透:
– 使用布隆过滤器
– 拦截不存在的商品ID
– 减少数据库压力
b. 缓存击穿:
– 使用互斥锁
– 热点商品永不过期
– 避免大量请求打到数据库
c. 缓存雪崩:
– 过期时间随机化
– 多级缓存(本地缓存+Redis)
– 限流降级
d. 缓存一致性:
– 使用Cache Aside模式
– 更新数据库后删除缓存
– 使用Canal监听binlog
3. 性能优化:
– 使用Pipeline批量操作
– 使用连接池
– 合理设置过期时间
– 避免大key
4. 高可用:
– 使用哨兵模式
– 主从复制
– 自动故障转移
"
6.2 常见追问
Q1:Redis为什么快?
"内存存储、单线程、IO多路复用、高效数据结构。"
Q2:如何解决缓存穿透?
"使用布隆过滤器或缓存空值。"
Q3:如何保证缓存一致性?
"使用Cache Aside模式,更新数据库后删除缓存。"
Q4:Redis分布式锁如何实现?
"使用SETNX+过期时间,Lua脚本释放锁,推荐使用Redisson。"
Q5:RDB和AOF的区别?
"RDB是快照,恢复快但可能丢失数据。AOF是日志,数据完整但恢复慢。"
七、学习检查清单
- 我掌握Redis 5种基本数据类型和使用场景
- 我理解Redis快的原因
- 我掌握缓存三大问题的解决方案
- 我理解缓存一致性问题
- 我理解RDB和AOF的区别
- 我掌握Redis分布式锁的实现
- 我理解Redis集群方案
- 我能用"总分总"结构回答Redis问题
- 我能在面试中清晰描述Redis相关项目经验
八、练习题
8.1 基础练习
1. 实现一个商品缓存功能
2. 实现一个购物车功能
3. 实现一个排行榜功能
4. 解决缓存穿透问题
5. 解决缓存击穿问题
8.2 进阶练习
1. 实现Redis分布式锁
2. 实现缓存一致性方案
3. 实现多级缓存
4. 优化Redis性能
5. 搭建Redis集群
8.3 综合练习
1. 设计一个完整的缓存方案,包括:
– 缓存策略
– 缓存问题解决
– 缓存一致性
– 性能优化
– 高可用
2. 实现一个秒杀系统,要求:
– 使用Redis缓存商品信息
– 使用分布式锁保证库存不超卖
– 解决缓存问题
– 提供完整的代码实现
3. 分析并优化一个Redis慢查询,要求:
– 分析原因
– 提供优化方案
– 对比优化前后性能
九、下一步学习
- 07-消息队列面试题
- 08-分布式系统面试题
- 05-数据库面试题精选
学习建议:



