Jave-Redis

Jave-Redis

Redis介绍

基于内存key-value 结构数据库

特点:

  • 基于内存存储,读写性能高
  • 适合存储热点数据(热点商品、资讯)

数据类型

key是 字符串类型
value有5种常用数据类型:

  • 字符串 string
  • 哈希 hash (hashMap)
  • 列表 list (LinkedList)
  • 集合 set (HashSet)
  • 有序集合 sorted set / zset (集合中每个元素关联一个分数「score」 根据分数升序排序,没有重复元素)

字符串

根据字符串的格式不同,可以分为三类

  • string
  • int
  • float

字符串操作命令
alt text

哈希操作命令

alt text

列表操作命令

alt text

集合操作命令

Redis set 是string类型的无序集合,集合成员是唯一的,不能出现重复的数据
alt text

有序集合操作命令

alt text

通用操作命令

alt text
alt text

Redis 缓存注解

alt text

存入缓存数据: @Cacheable(cacheNames = "setmealCache", key = "#categoryId")

清除指定key的缓存数据: @CacheEvict(cacheNames = "setmealCache",key = "#setmealDTO.categoryId")

清除全部缓存数据: @CacheEvict(cacheNames = "setmealCache",allEntries = true)

Redis 缓存注解常见使用思路

alt text

RedisTemplate 两种序列化实践方案

alt text

添加Redis缓存

alt text

alt text

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

@Autowired
private StringRedisTemplate stringRedisTemplate;

@Override
public Result queryShopById(Long id) {
String key = "cache:shop:" + id;

//1. 查询缓存
String shopJson = stringRedisTemplate.opsForValue().get(key);

//2.查到了缓存
if(StrUtil.isNotBlank(shopJson)){
Shop shop = JSONUtil.toBean(shopJson,Shop.class); //将redis中的json字符串变成对应的对象
return Result.ok(shop);
}
//3.没查到缓存,就去数据库里找
Shop shop = getById(id); //mybatis-plus

//4. 数据库也没有,就返回错误
if(shop == null){
return Result.fail("店铺不存在");
}

//5. 将数据写入redis
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop)); //将对象转换成json字符串存入redis

return Result.ok(shop);


}
}

缓存穿透

缓存穿透是指 当客户端请求的数据在数据库和redis缓存中都没有的时候,这些缓存永远不会生效,从而导致一直请求数据库。

解决方案:

  1. 缓存空对象

alt text

  1. 布隆过滤
    alt text

缓存雪崩

同一时间,大量请求无法使用缓存(key集体过期,缓存服务器宕机),像雪崩一样冲向数据库

解决方案:

  1. 设置随机的一个过期时间

缓存击穿

热点的key过期,导致一瞬间大量访问该key的请求打到数据库 。该key有两个特征:1. 被大量请求访问 2. 缓存重建业务复杂(在重建长时间里,大量请求透过,多次进行缓存重建)


Jave-Redis
https://cs-lb.github.io/2024/11/05/Java/Jave-Redis/
作者
Liu Bo
发布于
2024年11月5日
许可协议