参照有赞TMC框架原理简单实现多级缓存

本文涉及的产品
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
云数据库 Tair(兼容Redis),内存型 2GB
简介: 项目场景:有位同事因为缓存被后台删除,导致一堆高并发请求直接怼到DB上,导致数据库cpu 100%

项目场景:

有位同事因为缓存被后台删除,导致一堆高并发请求直接怼到DB上,导致数据库cpu 100%

解决方案:
处理缓存击穿问题:像布隆过滤器,或者说提前设置热点key
就是热点key检测,这里谈到了有赞TMC框架多级缓存以及它的热点key的发现
个人简单实现相关原理
本地变量
像热点key储存,本地缓存以及相关参数设置设置。 在这里插入图片描述

获取本地缓存的数据
在这里插入图片描述 解释: 1.由于是分布式环境,所以先查询下这个key有没有被删除过 2.直接走本地缓存 3.如果是后台数据被修改,redis这个标识被修改到了,我们需要重新加载数据库的数据更新到本地缓存中,以及set到redis中

数据一致性问题
就是redis缓存跟本地缓存一致性问题,我的想法是惰性就行更新,如果有人去读取,先返回本地缓存的旧数据,后面再进行更新,也就是实现最终一致性问题。

存在问题

就是这里的flag在更新之后会变成0,我这里的的优化方案是:采用nacos的版本控制,redis有一份版本,本地也有一份版本,如果说redis上的版本跟本地缓存的版本有所不一样,那么就进行修改本地缓存,以及将最新的版本更新到本地缓存中。

这样的话就不会导致说一台机器把redis设置为0,另一台本地缓存就不会变了。

优化方案

使用nacos版本修改的原理来控制不同机器的本地缓存更新
更新的时候可以加个分布式锁,获得锁才能去查数据库,防止高并发查崩数据库。其次在把这个数据塞到redis还有本地缓存中。
设置缓存的值
加粗样式

删除缓存
在这里插入图片描述

统一获取缓存的方法
/**

 * 统一获取缓存数据
 *
 * @param key
 * @return
 */
public String getRedisByKey(String key) {
    //计数
    stringRedisTemplate.opsForValue().increment(key + ":incr", 1);
    //5秒过期
    stringRedisTemplate.expire(key + ":incr", 10, TimeUnit.SECONDS);
    String count = stringRedisTemplate.opsForValue().get(key + ":incr");
    if (count != null && Integer.valueOf(count) > 2) {
        if (map.get(key) != null) {
            System.out.println("命中热点key....");
            return getCacheValue(key);
        }
        //2写死,表示5秒内get超过2次,定义为热点key
        map.put(key, "true");
        if (stringRedisTemplate.getExpire(key, TimeUnit.SECONDS) < 10) {
            //自动延期
            System.out.println("自动延期");
            stringRedisTemplate.expire(key, 20, TimeUnit.SECONDS);
        }
    } else {
        map.remove(key);
        String result = stringRedisTemplate.opsForValue().get(key);
        if (result == null) {
            String value = a(key);
            setRedisByKey(key, value, 20L);
            return value;
        }
        System.out.println("直接走redis");
        return result;
    }
    return getCacheValue(key);
}

前面是进行简单的计数法来保存这个热点key,如果命中热点key直接读本地缓存,否则读redis,没有的话再去读DB。

重点
如果是热点key的话,那么就会去判断它过期时间,如果不够的话会自动给它进行续期。

优化
比如说热点key的统计方式,这里只是简单的redis+1,如果高级一点就是时间滑窗统计热点key
这里是封装redistemplate查询的方案,比较好的是有一个特有的分布式集群来收集这些redis查询,redis key过期、设置、删除操作等等,会更好。
在删除热点key map那里也是需要再优化的,就是如果说重新这个key在接下来的时间内不那么火热,那么剔除map对应的key。
所有代码
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Component
public class RedisManagement {

@Autowired
private StringRedisTemplate stringRedisTemplate;

ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();

private LoadingCache<String, String> graphs = CacheBuilder.newBuilder()
        .maximumSize(1000)
        .expireAfterWrite(1, TimeUnit.HOURS)
        .refreshAfterWrite(1, TimeUnit.HOURS)
        .build(
                new CacheLoader<String, String>() {
                    @Override
                    public String load(String key) {
                        return a(key);
                    }
                });

private String getCacheValue(String key) {
    String result;
    String flag = stringRedisTemplate.opsForValue().get(key + ":flag");
    try {
        System.out.println("走本地缓存");
        result = graphs.get(key);
    } catch (ExecutionException e) {
        System.out.println("出现报错:" + e);
        return null;
    }
    //不为空还有已经删除状态
    if (flag != null && "1".equals(flag)) {
        //更新本地缓存的
        graphs.refresh(key);
        //设置删除标识为未删除
        stringRedisTemplate.opsForValue().set(key + ":flag", "0");
    }
    return result;
}

/**
 * 统一设置缓存
 *
 * @param key
 * @param value
 * @return
 */
public void setRedisByKey(String key, String value, long time) {
    //设置删除标识为未删除
    stringRedisTemplate.opsForValue().set(key + ":flag", "0");
    stringRedisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
}

/**
 * 统一删除缓存
 *
 * @param key
 * @return
 */
public Boolean delRedisByKey(String key) {
    //设置删除标识为删除
    stringRedisTemplate.opsForValue().set(key + ":flag", "1");
    return stringRedisTemplate.delete(key);
}

/**
 * 统一获取缓存数据
 *
 * @param key
 * @return
 */
public String getRedisByKey(String key) {
    //计数
    stringRedisTemplate.opsForValue().increment(key + ":incr", 1);
    //5秒过期
    stringRedisTemplate.expire(key + ":incr", 10, TimeUnit.SECONDS);
    String count = stringRedisTemplate.opsForValue().get(key + ":incr");
    if (count != null && Integer.valueOf(count) > 2) {
        if (map.get(key) != null) {
            System.out.println("命中热点key....");
            return getCacheValue(key);
        }
        //2写死,表示5秒内get超过2次,定义为热点key
        map.put(key, "true");
        if (stringRedisTemplate.getExpire(key, TimeUnit.SECONDS) < 10) {
            //自动延期
            System.out.println("自动延期");
            stringRedisTemplate.expire(key, 20, TimeUnit.SECONDS);
        }
    } else {
        map.remove(key);
        String result = stringRedisTemplate.opsForValue().get(key);
        if (result == null) {
            String value = a(key);
            setRedisByKey(key, value, 20L);
            return value;
        }
        System.out.println("直接走redis");
        return result;
    }
    return getCacheValue(key);
}

/**
 * 初始化本地缓存数据
 *
 * @param key
 * @return
 */
private String a(String key) {
    System.out.println("查db");
    //执行不同逻辑
    if (key.startsWith("activity")) {
        //查数据库
        return "activity";
    } else if (key.startsWith("content")) {
        //查数据库
        return "content";
    } else {
        return "haha";
    }
}

}

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
1月前
|
缓存 Java 开发工具
Spring是如何解决循环依赖的?从底层源码入手,详细解读Spring框架的三级缓存
三级缓存是Spring框架里,一个经典的技术点,它很好地解决了循环依赖的问题,也是很多面试中会被问到的问题,本文从源码入手,详细剖析Spring三级缓存的来龙去脉。
134 24
Spring是如何解决循环依赖的?从底层源码入手,详细解读Spring框架的三级缓存
|
1月前
|
缓存 NoSQL 应用服务中间件
SpringCloud基础8——多级缓存
JVM进程缓存、Lua语法、OpenResty、Nginx本地缓存、缓存同步、Canal
SpringCloud基础8——多级缓存
|
2月前
|
缓存 NoSQL Java
SpringBoot的三种缓存技术(Spring Cache、Layering Cache 框架、Alibaba JetCache 框架)
Spring Cache 是 Spring 提供的简易缓存方案,支持本地与 Redis 缓存。通过添加 `spring-boot-starter-data-redis` 和 `spring-boot-starter-cache` 依赖,并使用 `@EnableCaching` 开启缓存功能。JetCache 由阿里开源,功能更丰富,支持多级缓存和异步 API,通过引入 `jetcache-starter-redis` 依赖并配置 YAML 文件启用。Layering Cache 则提供分层缓存机制,需引入 `layering-cache-starter` 依赖并使用特定注解实现缓存逻辑。
582 1
SpringBoot的三种缓存技术(Spring Cache、Layering Cache 框架、Alibaba JetCache 框架)
|
2月前
|
存储 缓存 算法
缓存优化利器:5分钟实现 LRU Cache,从原理到代码!
嗨,大家好!我是你们的技术小伙伴——小米。今天带大家深入了解并手写一个实用的LRU Cache(最近最少使用缓存)。LRU Cache是一种高效的数据淘汰策略,在内存有限的情况下特别有用。本文将从原理讲起,带你一步步用Java实现一个简单的LRU Cache,并探讨其在真实场景中的应用与优化方案,如线程安全、缓存持久化等。无论你是初学者还是有一定经验的开发者,都能从中受益。让我们一起动手,探索LRU Cache的魅力吧!别忘了点赞、转发和收藏哦~
48 2
|
2月前
|
缓存 监控 网络协议
DNS缓存中毒原理
【8月更文挑战第17天】
82 1
|
2月前
|
缓存 分布式计算 Java
详细解读MapReduce框架中的分布式缓存
【8月更文挑战第31天】
30 0
|
2月前
|
存储 缓存 数据库
微服务+多级缓存:性能起飞的秘籍
【8月更文挑战第29天】在当今快速迭代的软件开发领域,高性能与可扩展性是企业应用不可或缺的两大支柱。微服务架构与多级缓存策略的完美结合,正是这一追求下的璀璨明珠。今天,我们将深入探讨这一组合如何助力系统性能“起飞”,并在实际工作学习中成为技术升级的关键推手。
53 0
|
2月前
|
开发框架 缓存 NoSQL
基于SqlSugar的开发框架循序渐进介绍(17)-- 基于CSRedis实现缓存的处理
基于SqlSugar的开发框架循序渐进介绍(17)-- 基于CSRedis实现缓存的处理
|
2月前
|
存储 缓存 NoSQL
微服务缓存原理与最佳实践
微服务缓存原理与最佳实践
|
17天前
|
存储 缓存 NoSQL
数据的存储--Redis缓存存储(一)
数据的存储--Redis缓存存储(一)
53 1