Redis缓存的基本概念和使用

什么是缓存

缓存时数据交换的缓冲区,存储数据的临时区,读写性能较好。
例如计算机的三级缓存。CPU的计算速度超过内存的读写速度,为了平衡两者速度,使用了三级缓存,把经常需要读写的数据放到三级缓存中。
例如DNS缓存,浏览器缓存,nginx缓存,JVM进程缓存,Redis缓存,数据库缓存等。
缓存作用:
1、降低后端负载。
2、提高读写效率,降低响应时间。
缓存成本:
1、缓存一致性。
2、复杂度。例如缓存穿透,缓存击穿,缓存雪崩等问题使代码复杂度提升。
3、运维成本。

Redis缓存

客户端先请求Redis缓存,命中缓存则直接返回,没有命中再请求数据库,若数据不存在则返回404,如果数据存在则把新数据写到Redis缓存中,最后返回数据。
例如店铺信息缓存如下:

@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Object queryById(Long id) {
        String key = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if (! StrUtil.isEmpty(shopJson)) {
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(shop);
        }
        Shop shop = getById(id);
        if (shop == null) {
            return Result.fail("店铺不存在!");
        }
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop));
        stringRedisTemplate.expire(key, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return Result.ok(shop);
    }
}

缓存更新策略

1、内存淘汰
使用Redis的内存淘汰策略,内存不足时自己淘汰部分数据,下次查询时更新缓存。
应用于一致性要求低,几乎不需要维护成本的场景。
2、超时剔除
给数据添加过期时间,到期后自动删除缓存,下次查询时更新缓存。
应用于一致性要求一般,维护成本较低的场景。
3、主动更新
编写业务逻辑,在修改数据库数据时,更新缓存。
适用一致性较好,维护成本较高的场景。

业务场景:
低一致性需求:使用内存淘汰,比如店铺类型的查询缓存。
高一致性需求:使用主动更新,并添加超时剔除作为兜底,例如店铺详情的缓存。

主动更新策略有哪些?
1、旁路缓存,Cache Aside
缓存调用者在更新数据库时更新缓存。相对可控,实际使用较多
2、读穿/写穿,Read/Write Through
缓存和数据库整合成一个服务,调用者无需关心数据库和缓存一致性。
3、读后写,Write Behind Caching
调用者只操作缓存,其他线程异步地将数据从缓存持久化到数据库。

旁路缓存具体方案?
1、删除缓存还是更新缓存?
使用删除缓存,因为如果使用更新缓存,每次更新数据库都要更新缓存,如果中间没有读取,那么无效写操作太多。
2、如何保证操作数据库和缓存的同时成功和失败?
单体系统,将数据库和缓存的操作放在一个事务中。
分布式系统,使用TCC等分布式事务。
3、先操作缓存还是先操作数据库?
根据:更新数据库时间更慢,删除缓存时间更快。

如果先删缓存,后更新数据库。
线程1刚把缓存删除,还没有更新缓存,线程2查询缓存未命中,会查询数据库旧值并且更新到缓存中,导致缓存数据是旧值。

如果先更新数据库,再删除缓存。
缓存失效,线程1查询缓存未命中,查询到数据库,线程2刚好修改数据库,并且删除缓存,线程2将旧数据写入缓存。
发生概率较小,因为写入缓存时间较短,需要在线程1查询完数据库写入缓存前,把线程2的更新数据库和删除缓存都完成概率较小。

例如,实现查询商铺的查询缓存添加主动更新和超时剔除策略。
1、查询时,如果缓存未命中,则查询数据库,并且写入缓存,设置超时时间。
2、更新时,先修改数据库,后删除缓存。

@Override
public Object queryById(Long id) {
    String key = CACHE_SHOP_KEY + id;
    String shopJson = stringRedisTemplate.opsForValue().get(key);
    if (! StrUtil.isEmpty(shopJson)) {
        Shop shop = JSONUtil.toBean(shopJson, Shop.class);
        return Result.ok(shop);
    }
    Shop shop = getById(id);
    if (shop == null) {
        return Result.fail("店铺不存在!");
    }
    stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
    return Result.ok(shop);
}

@Override
@Transactional
public Result updateShop(Shop shop) {
    Long id = shop.getId();
    if (id == null) {
        return Result.fail("店铺id不能为空!");
    }
    updateById(shop);
    String key = CACHE_SHOP_KEY + id;
    stringRedisTemplate.delete(key);
    return Result.ok();
}

缓存穿透

缓存穿透:客户端请求的数据在缓存和数据库中都不存在,缓存永远不会生效,会打到数据库。
解决:
1、缓存空对象。
优点:实现简单。
缺点:额外内存消耗,可能有短期数据不一致。
2、布隆过滤器。
优点:内存消耗更小。
缺点:实现复杂,存在误判,不能解决删除元素问题。

编码实现,这里使用缓存空对象。

@Override
public Object queryById(Long id) {
    String key = CACHE_SHOP_KEY + id;
    String shopJson = stringRedisTemplate.opsForValue().get(key);
    if (! StrUtil.isNotBlank(shopJson)) {
        Shop shop = JSONUtil.toBean(shopJson, Shop.class);
        return Result.ok(shop);
    }
    //命中之前缓存的空字符串
    if ("".equals(shopJson)) {
        return Result.fail("店铺不存在!");
    }
    Shop shop = getById(id);
    if (shop == null) {
        //写入空值解决缓存穿透
        stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
        return Result.fail("店铺不存在!");
    }
    stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
    return Result.ok(shop);
}

缓存雪崩

缓存雪崩:同一时段大量缓存key同时失效,或者Redis服务宕机,导致大量请求达到数据库。
解决:
1、给不同key的过期时间ttl设置随机值。
2、使用Redis集群提高服务可用性。
3、添加降级限流策略。
4、添加多级缓存。

缓存击穿

缓存击穿:热点key突然失效,无数请求瞬间达到数据库带来巨大冲击。
解决:
1、互斥锁。重建缓存时,使用一个锁保证只有一个线程能重建缓存。可以结合两次if判断进行双重检查防止后面线程获取锁的开销。
优点:实现简单,保证一致性。
缺点:性能受影响,可能有死锁风险。
2、逻辑过期。即不设置ttl,key永不过期,但是在value中设置expire字段。当线程1发现key过期时,拿到互斥锁,并开启新线程重建缓存。其他线程获取锁失败时直接拿旧数据。
优点:线程无需等待,性能较好。
缺点:一致性更低,有额外内存消耗。
区别:逻辑过期也使用了互斥锁,但是它和互斥锁的区别在于,过期数据依然在Redis中,因此其他线程可以先使用旧数据。

例子:根据id查询商铺,使用互斥锁解决缓存击穿。

    public Shop queryWithMutex(Long id) {
        String key = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopJson)) {
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //命中之前缓存的空字符串,解决缓存穿透
        if ("".equals(shopJson)) {
            return null;
        }
        Shop shop = null;
        String lockKey = LOCK_SHOP_KEY + id;
        try {
            while (!tryLock(lockKey)) {
                Thread.sleep(50);
            }
            //双重检查
            shopJson = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isNotBlank(shopJson)) {
                return JSONUtil.toBean(shopJson, Shop.class);
            }
            //命中之前缓存的空字符串,解决缓存穿透
            if ("".equals(shopJson)) {
                return null;
            }
            shop = getById(id);
            if (shop == null) {
                //写入空值解决缓存穿透
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unLock(lockKey);
        }
        return shop;
    }

例子:根据id查询商铺,逻辑过期解决缓存击穿例子:

public class RedisData {
    private LocalDateTime expireTime;
    private Object data;
}
public void saveShop2Redis(Long id, Long expireSeconds) {
    Shop shop = getById(id);
    RedisData redisData = new RedisData();
    redisData.setData(shop);
    redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
    stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
}

//逻辑过期解决缓存击穿
public Shop queryWithLogicalExpire(Long id) {
    String key = CACHE_SHOP_KEY + id;
    String shopJson = stringRedisTemplate.opsForValue().get(key);
    if (StrUtil.isBlank(shopJson)) {
        return null;
    }
    RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
    LocalDateTime expireTime = redisData.getExpireTime();
    JSONObject jsonObject = (JSONObject) redisData.getData();
    Shop shop = JSONUtil.toBean(jsonObject, Shop.class);
    if (expireTime.isAfter(LocalDateTime.now())) {
        return shop;
    }
    String lockKey = LOCK_SHOP_KEY + id;
    if (tryLock(lockKey)) {
        CACHE_REBUILD_EXECUTOR.execute(()->{
            try {
                saveShop2Redis(id, 30L);
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                unLock(lockKey);
            }
        });

    }
    return shop;
}

缓存工具类封装

缓存穿透,缓存击穿,缓存雪崩等业务逻辑较复杂,如果每次使用缓存都需要写这部分代码,可以考虑把这部分代码封装成一个工具类。
方法1:将Java对象序列化成JSON字符串并且存储在string类型的Redis中,并且可以设置过期时间。
方法2:将Java对象序列化成JSON字符串并且存储在string类型的Redis中,可以设置逻辑过期时间,解决缓存击穿问题。
方法3:根据指定key查询缓存,并且反序列化成指定类型,利用缓存空值的方式解决缓存穿透。
方法4:根据指定key查询缓存,并且反序列化成执行类型,利用逻辑过期解决缓存击穿。

@Slf4j
@Component
public class CacheClient {

    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public void set(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    public <R, ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallBack,
                                          Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)) {
            return JSONUtil.toBean(json, type);
        }
        if ("".equals(json)) {
            return null;
        }
        R r = dbFallBack.apply(id);
        if (r == null) {
            //写入空值解决缓存穿透
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        set(key, r, time, unit);
        return r;
    }

    public <R, ID> R queryWithLogicalExpire(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallBack,
                                            Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(json)) {
            return null;
        }
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        JSONObject jsonObject = (JSONObject) redisData.getData();
        R r = JSONUtil.toBean(jsonObject, type);
        if (expireTime.isAfter(LocalDateTime.now())) {
            return r;
        }
        String lockKey = LOCK_SHOP_KEY + id;
        if (tryLock(lockKey)) {
            CACHE_REBUILD_EXECUTOR.execute(()->{
                try {
                    R r1 = dbFallBack.apply(id);
                    setWithLogicalExpire(key, r1, time, unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unLock(lockKey);
                }
            });

        }
        return r;
    }

    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }
}

相关推荐

  1. Redis缓存基本概念使用

    2024-05-13 14:50:10       9 阅读
  2. 缓存】一、Redis基本使用与Redisson分布式锁

    2024-05-13 14:50:10       24 阅读
  3. Git 基本概念使用方式

    2024-05-13 14:50:10       38 阅读
  4. TensorFlow 基本概念使用场景

    2024-05-13 14:50:10       40 阅读
  5. Git 基本概念使用方式

    2024-05-13 14:50:10       35 阅读
  6. TensorFlow 基本概念使用场景。

    2024-05-13 14:50:10       40 阅读
  7. Git 基本概念使用方式。

    2024-05-13 14:50:10       35 阅读
  8. TensorFlow 基本概念使用场景

    2024-05-13 14:50:10       38 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-05-13 14:50:10       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-05-13 14:50:10       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-05-13 14:50:10       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-05-13 14:50:10       18 阅读

热门阅读

  1. QT作业5

    QT作业5

    2024-05-13 14:50:10      11 阅读
  2. C语言笔记13

    2024-05-13 14:50:10       10 阅读
  3. 商业时代杂志社投稿信箱邮箱

    2024-05-13 14:50:10       9 阅读
  4. hive自定义函数

    2024-05-13 14:50:10       7 阅读
  5. OpenCV 滤波方法总结

    2024-05-13 14:50:10       10 阅读
  6. golang函数默认参数

    2024-05-13 14:50:10       9 阅读
  7. mysql编程1

    2024-05-13 14:50:10       9 阅读