使用Redis实现缓存穿透的解决方案

本文涉及的产品
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
云数据库 Tair(兼容Redis),内存型 2GB
简介: 使用Redis实现缓存穿透的解决方案

使用Redis实现缓存穿透的解决方案

在缓存系统中,缓存穿透是指访问不存在的数据,导致请求直接穿透缓存层,直接访问数据库,造成数据库压力过大,甚至影响系统稳定性。本文将深入探讨如何使用Redis实现有效的缓存穿透解决方案。

1. 基本概念和问题背景

缓存穿透通常发生在恶意攻击或者大量请求查询不存在的数据时。例如,某些恶意用户不断查询不存在的用户信息,导致每次请求都要访问数据库,严重影响系统性能。为了解决这个问题,我们可以引入布隆过滤器和空值缓存等技术手段。

2. 使用布隆过滤器过滤无效请求

布隆过滤器是一种高效的数据结构,用于快速判断一个元素是否存在于集合中。在缓存层加入布隆过滤器,可以快速过滤掉不存在的请求,避免对数据库的直接查询。

package cn.juwatech.example;

import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Service
public class BloomFilterService {
   

    @Autowired
    private RedisService redisService;

    private BloomFilter<String> bloomFilter;

    @PostConstruct
    public void init() {
   
        int expectedInsertions = 1000000;
        double fpp = 0.01; // False Positive Probability
        bloomFilter = BloomFilter.create(Funnels.stringFunnel(), expectedInsertions, fpp);
    }

    public boolean mightContain(String key) {
   
        return bloomFilter.mightContain(key);
    }

    public void put(String key) {
   
        bloomFilter.put(key);
    }
}

3. 空值缓存策略

当查询的数据确实不存在时,不直接访问数据库,而是将空结果设置到缓存中,设置合理的过期时间,避免空值缓存过久占用内存资源。

package cn.juwatech.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class CacheService {
   

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public Object get(String key) {
   
        return redisTemplate.opsForValue().get(key);
    }

    public void set(String key, Object value, long timeout, TimeUnit unit) {
   
        redisTemplate.opsForValue().set(key, value, timeout, unit);
    }

    public void setNull(String key, long timeout, TimeUnit unit) {
   
        redisTemplate.opsForValue().set(key, "", timeout, unit); // Placeholder for null value
    }

    public boolean exists(String key) {
   
        return redisTemplate.hasKey(key);
    }
}

4. 实现缓存穿透解决方案

结合布隆过滤器和空值缓存策略,实现完整的缓存穿透解决方案。在查询前先通过布隆过滤器判断是否存在于缓存中,如果存在则直接返回缓存数据;如果不存在,则进行数据库查询,查询结果为空时设置空值缓存,并设置较短的过期时间,避免重复查询。

package cn.juwatech.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class DataService {
   

    @Autowired
    private CacheService cacheService;

    @Autowired
    private DatabaseService databaseService;

    @Autowired
    private BloomFilterService bloomFilterService;

    public Object getData(String key) {
   
        if (bloomFilterService.mightContain(key)) {
   
            if (cacheService.exists(key)) {
   
                return cacheService.get(key);
            } else {
   
                Object data = databaseService.getData(key);
                if (data != null) {
   
                    cacheService.set(key, data, 10, TimeUnit.MINUTES); // Example: cache for 10 minutes
                    return data;
                } else {
   
                    cacheService.setNull(key, 1, TimeUnit.MINUTES); // Example: cache null value for 1 minute
                    return null;
                }
            }
        } else {
   
            return null; // Request not in bloom filter, likely invalid
        }
    }
}

通过以上实现,我们能够有效地解决缓存穿透问题,提升系统的性能和稳定性,确保对数据库的请求能够得到有效地缓存和利用。

相关实践学习
基于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
相关文章
|
21天前
|
canal 缓存 NoSQL
Redis缓存与数据库如何保证一致性?同步删除+延时双删+异步监听+多重保障方案
根据对一致性的要求程度,提出多种解决方案:同步删除、同步删除+可靠消息、延时双删、异步监听+可靠消息、多重保障方案
Redis缓存与数据库如何保证一致性?同步删除+延时双删+异步监听+多重保障方案
|
22天前
|
存储 NoSQL Redis
SpringCloud基础7——Redis分布式缓存,RDB,AOF持久化+主从+哨兵+分片集群
Redis持久化、RDB和AOF方案、Redis主从集群、哨兵、分片集群、散列插槽、自动手动故障转移
SpringCloud基础7——Redis分布式缓存,RDB,AOF持久化+主从+哨兵+分片集群
|
5天前
|
存储 缓存 NoSQL
解决Redis缓存击穿问题的技术方法
解决Redis缓存击穿问题的技术方法
19 2
|
5天前
|
缓存 NoSQL Redis
解决 Redis 缓存穿透问题的有效方法
解决 Redis 缓存穿透问题的有效方法
17 2
|
5天前
|
存储 缓存 NoSQL
Redis 大 Key 对持久化的影响及解决方案
Redis 大 Key 对持久化的影响及解决方案
13 1
|
5天前
|
缓存 NoSQL 前端开发
16)缓存雪崩、缓存击穿、缓存穿透
16)缓存雪崩、缓存击穿、缓存穿透
13 0
|
2月前
|
缓存 NoSQL Redis
【Azure Redis 缓存】Redission客户端连接Azure:客户端出现 Unable to send PING command over channel
【Azure Redis 缓存】Redission客户端连接Azure:客户端出现 Unable to send PING command over channel
|
2月前
|
缓存 NoSQL 网络协议
【Azure Redis 缓存】Lettuce 连接到Azure Redis服务,出现15分钟Timeout问题
【Azure Redis 缓存】Lettuce 连接到Azure Redis服务,出现15分钟Timeout问题
【Azure Redis 缓存】Lettuce 连接到Azure Redis服务,出现15分钟Timeout问题
|
2月前
|
缓存 NoSQL Java
Redis深度解析:解锁高性能缓存的终极武器,让你的应用飞起来
【8月更文挑战第29天】本文从基本概念入手,通过实战示例、原理解析和高级使用技巧,全面讲解Redis这一高性能键值对数据库。Redis基于内存存储,支持多种数据结构,如字符串、列表和哈希表等,常用于数据库、缓存及消息队列。文中详细介绍了如何在Spring Boot项目中集成Redis,并展示了其工作原理、缓存实现方法及高级特性,如事务、发布/订阅、Lua脚本和集群等,帮助读者从入门到精通Redis,大幅提升应用性能与可扩展性。
60 0
|
2月前
|
缓存 NoSQL Redis
【Azure Redis 缓存】使用StackExchange.Redis,偶发ERROR - Timeout performing HSET (15000ms)
【Azure Redis 缓存】使用StackExchange.Redis,偶发ERROR - Timeout performing HSET (15000ms)
下一篇
无影云桌面