Redis缓存设计与性能优化

多级缓存架构

缓存设计

缓存穿透

  • 缓存穿透是指查询一个根本不存在的数据, 缓存层和存储层都不会命中, 通常出于容错的考虑, 如果从存储层查不到数据则不写入缓存层。
  • 缓存穿透将导致不存在的数据每次请求都要到存储层去查询, 失去了缓存保护后端存储的意义。

造成缓存穿透的基本原因有两个

  • 自身业务代码或者数据出现问题。
  • 一些恶意攻击、 爬虫等造成大量空命中。

缓存穿透问题解决方案

1、缓存空对象

java 复制代码
String get(String key) {
    // 从缓存中获取数据
    String cacheValue = cache.get(key);
    // 缓存为空
    if (StringUtils.isBlank(cacheValue)) {
        // 从存储中获取
        String storageValue = storage.get(key);
        cache.set(key, storageValue);
        // 如果存储数据为空, 需要设置一个过期时间(300秒)
        if (storageValue == null) {
            cache.expire(key, 60 * 5);
        }
        return storageValue;
    } else {
        // 缓存非空
        return cacheValue;
    }
}
相关推荐
X***C86217 小时前
Redis开启远程连接
数据库·redis·缓存
管理大亨18 小时前
MySQL数据实时同步Redis全攻略
数据库·redis·mysql
8***848219 小时前
macOS安装Redis
数据库·redis·macos
g***557521 小时前
Redis 通用命令
前端·redis·bootstrap
c***212921 小时前
ubuntu 安装 Redis
linux·redis·ubuntu
l***061 天前
Redis--模糊查询--方法实例
数据库·redis·缓存
i***11861 天前
springboot使用redis
spring boot·redis·后端
爬山算法1 天前
Redis(154)Redis的数据一致性如何保证?
数据库·redis·bootstrap
光军oi1 天前
面试redis篇———缓存击穿和缓存雪崩问题及解决策略
redis·缓存·面试
yeshihouhou1 天前
redis主从复制
数据库·redis·缓存