Redis之缓存击穿问题解决方案

文章目录

一、书接上文

Redis之缓存雪崩问题解决方案

二、介绍

缓存击穿就是大量并发访问同一个热点数据,一旦这个热点数据缓存失效,则请求压力都来到数据库。

三、解决方案

1. 单例双检锁

java 复制代码
	@Override
    public CoursePublish getCoursePublishCache(Long courseId) {
        String key = "content:course:publish:" + courseId;
        //布隆过滤器
        boolean contains = bloomFilter.contains(key);
        if (!contains){
            return null;
        }
        //先查询redis
        Object object = redisTemplate.opsForValue().get(key);
        if (object != null){
            String string = object.toString();
            CoursePublish coursePublish = JSON.parseObject(string, CoursePublish.class);
            return coursePublish;
        }else {
            //后查询数据库
            //加锁,防止缓存击穿
            synchronized (this){
                //单例双检锁
                object = redisTemplate.opsForValue().get(key);
                if (object != null){
                    String string = object.toString();
                    CoursePublish coursePublish = JSON.parseObject(string, CoursePublish.class);
                    return coursePublish;
                }
                CoursePublish coursePublish = getCoursePublish(courseId);
                if (coursePublish != null) {
                	bloomFilter.add(key);
                    redisTemplate.opsForValue().set(key, JSON.toJSONString(coursePublish));
                } else {
                    int timeout = 10 + new Random().nextInt(20);
                    redisTemplate.opsForValue().set(key, JSON.toJSONString(coursePublish), timeout, TimeUnit.SECONDS);
                }
                return coursePublish;
            }
        }
    }

2. 缓存预热和定时任务

使用缓存预热,把数据提前放入缓存,然后根据过期时间,发布合理的定时任务,主动去更新缓存,让热点数据永不过期。

相关推荐
jiayou648 小时前
KingbaseES 表级与列级加密完全指南
数据库·后端
用户3074596982071 天前
Redis 延时队列详解
redis
GBASE1 天前
G术时刻 |GBase 8s数据库事务并发控制之封锁技术介绍(下)
数据库
烤代码的吐司君1 天前
Redis 数据结构 ZSet, BIT, HyperLogLog,Geo 空间数据
redis·后端
xiezhr2 天前
逛GitHub发现了一款免费的带AI功能的数据库管理工具
数据库·ai编程·dba
吃糖的小孩3 天前
给 QQ AI 机器人设计“可控记忆”:会话摘要、手动长期记忆与角色卡边界
数据库
笃行3503 天前
金仓数据库数据安全双防线:静态存储加密与传输加密实战
数据库
笃行3503 天前
金仓数据库物理备份实战:sys_rman 全流程演练与误覆盖抢救
数据库
笃行3503 天前
金仓数据库逻辑备份实战:从全库导出到 Schema 替换的完整闭环
数据库