Redis(79)Redis的缓存穿透是什么?

缓存穿透的概念

缓存穿透(Cache Penetration)是指查询一个数据库中根本不存在的数据,而这些请求会直接穿透缓存,落到后端数据库中。由于这些数据在缓存中找不到,自然也不会写入缓存。所以每次请求都会去数据库查询,造成缓存形同虚设,失去了缓解数据库压力的作用。

缓存穿透问题通常出现在以下两种情况下:

  1. 恶意攻击:攻击者通过大量请求不存在的数据,导致请求直接落到数据库,造成数据库压力过大。
  2. 程序设计缺陷:由于程序设计不严谨,请求大量不存在的数据,导致缓存失效,直接查询数据库。

解决缓存穿透的方法

有几种常见的方法可以解决缓存穿透问题:

  1. 缓存空结果:当查询数据库结果为空时,将空结果也缓存起来,并设置一个较短的过期时间。
  2. 布隆过滤器:在缓存前增加布隆过滤器,快速判断请求的数据是否存在,如果不存在则直接返回结果,避免访问数据库。
  3. 参数校验:对请求参数进行严格校验,过滤掉明显无效的请求。

以下是详细的解决方案和示例代码:

1. 缓存空结果

当查询数据库返回空结果时,也将其缓存起来,并设置一个较短的过期时间,比如5分钟。

示例代码:

java 复制代码
import redis.clients.jedis.Jedis;
import com.fasterxml.jackson.databind.ObjectMapper;

public class CachePenetrationExample {
    private Jedis jedis;
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public CachePenetrationExample(Jedis jedis) {
        this.jedis = jedis;
    }

    public <T> T getCachedData(String key, Class<T> clazz, DataProvider<T> provider, int cacheTime) {
        try {
            String cacheValue = jedis.get(key);
            if (cacheValue != null) {
                if (cacheValue.equals("null")) {
                    return null;
                }
                return objectMapper.readValue(cacheValue, clazz);
            }

            T data = provider.getData();
            if (data == null) {
                jedis.setex(key, 300, "null"); // 缓存空结果5分钟
            } else {
                jedis.setex(key, cacheTime, objectMapper.writeValueAsString(data));
            }
            return data;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public interface DataProvider<T> {
        T getData();
    }

    public static void main(String[] args) {
        Jedis jedis = new Jedis("localhost", 6379);
        CachePenetrationExample cache = new CachePenetrationExample(jedis);

        String userId = "nonexistent";
        String cacheKey = "user:" + userId;
        int cacheTime = 3600; // 缓存 1 小时

        User user = cache.getCachedData(cacheKey, User.class, () -> {
            // 模拟数据库查询,返回null表示数据不存在
            return null;
        }, cacheTime);

        if (user == null) {
            System.out.println("User not found.");
        } else {
            System.out.println("User: " + user);
        }

        jedis.close();
    }

    static class User {
        private String id;
        private String name;
        private String email;

        // Getters and Setters

        @Override
        public String toString() {
            return "User{id='" + id + "', name='" + name + "', email='" + email + "'}";
        }
    }
}

2. 布隆过滤器

使用布隆过滤器快速判断数据是否存在。布隆过滤器是一种概率型数据结构,它能以较低的内存消耗判断一个元素是否存在某个集合中。虽然存在误判的可能,但不会漏判。

示例代码:

java 复制代码
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import redis.clients.jedis.Jedis;
import java.nio.charset.Charset;

public class BloomFilterExample {
    private Jedis jedis;
    private BloomFilter<String> bloomFilter;

    public BloomFilterExample(Jedis jedis, int expectedInsertions, double falsePositiveProbability) {
        this.jedis = jedis;
        this.bloomFilter = BloomFilter.create(Funnels.stringFunnel(Charset.defaultCharset()), expectedInsertions, falsePositiveProbability);
        // 初始化布隆过滤器,通常从数据库加载已有数据
        initializeBloomFilter();
    }

    private void initializeBloomFilter() {
        // 模拟加载数据
        bloomFilter.put("existingUser1");
        bloomFilter.put("existingUser2");
        // 真实环境中应从数据库加载
    }

    public <T> T getCachedData(String key, Class<T> clazz, DataProvider<T> provider, int cacheTime) {
        try {
            if (!bloomFilter.mightContain(key)) {
                return null;
            }

            String cacheValue = jedis.get(key);
            if (cacheValue != null) {
                if (cacheValue.equals("null")) {
                    return null;
                }
                return objectMapper.readValue(cacheValue, clazz);
            }

            T data = provider.getData();
            if (data == null) {
                jedis.setex(key, 300, "null"); // 缓存空结果5分钟
            } else {
                jedis.setex(key, cacheTime, objectMapper.writeValueAsString(data));
            }
            return data;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public interface DataProvider<T> {
        T getData();
    }

    public static void main(String[] args) {
        Jedis jedis = new Jedis("localhost", 6379);
        BloomFilterExample cache = new BloomFilterExample(jedis, 10000, 0.01);

        String userId = "nonexistent"; // 修改这个值来测试存在和不存在的情况
        String cacheKey = "user:" + userId;
        int cacheTime = 3600; // 缓存 1 小时

        User user = cache.getCachedData(cacheKey, User.class, () -> {
            // 模拟数据库查询,返回null表示数据不存在
            return null;
        }, cacheTime);

        if (user == null) {
            System.out.println("User not found.");
        } else {
            System.out.println("User: " + user);
        }

        jedis.close();
    }

    static class User {
        private String id;
        private String name;
        private String email;

        // Getters and Setters

        @Override
        public String toString() {
            return "User{id='" + id + "', name='" + name + "', email='" + email + "'}";
        }
    }
}

3. 参数校验

对请求参数进行严格校验,过滤掉明显无效的请求。例如,用户ID应为正整数,可以在程序中对用户ID进行校验,过滤掉不符合规则的请求。

示例代码:

java 复制代码
import redis.clients.jedis.Jedis;

public class ParameterValidationExample {
    private Jedis jedis;

    public ParameterValidationExample(Jedis jedis) {
        this.jedis = jedis;
    }

    public <T> T getCachedData(String key, Class<T> clazz, DataProvider<T> provider, int cacheTime) {
        try {
            if (!isValidKey(key)) {
                return null;
            }

            String cacheValue = jedis.get(key);
            if (cacheValue != null) {
                if (cacheValue.equals("null")) {
                    return null;
                }
                return objectMapper.readValue(cacheValue, clazz);
            }

            T data = provider.getData();
            if (data == null) {
                jedis.setex(key, 300, "null"); // 缓存空结果5分钟
            } else {
                jedis.setex(key, cacheTime, objectMapper.writeValueAsString(data));
            }
            return data;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private boolean isValidKey(String key) {
        // 仅示例性校验,实际中应视具体情况进行校验
        return key != null && key.matches("^user:\\d+$");
    }

    public interface DataProvider<T> {
        T getData();
    }

    public static void main(String[] args) {
        Jedis jedis = new Jedis("localhost", 6379);
        ParameterValidationExample cache = new ParameterValidationExample(jedis);

        String userId = "123"; // 正确的用户ID
        String cacheKey = "user:" + userId;
        int cacheTime = 3600; // 缓存 1 小时

        User user = cache.getCachedData(cacheKey, User.class, () -> {
            // 模拟数据库查询
            return getUserFromDatabase(userId);
        }, cacheTime);

        if (user == null) {
            System.out.println("User not found.");
        } else {
            System.out.println("User: " + user);
        }

        jedis.close();
    }

    private static User getUserFromDatabase(String userId) {
        // 模拟数据库查询
        User user = new User();
        user.setId(userId);
        user.setName("John Doe");
        user.setEmail("john.doe@example.com");
        return user;
    }

 
相关推荐
刘一说5 分钟前
Spring Boot 应用的指标收集与监控体系构建指南
java·spring boot·后端
冰_河1 小时前
《Nginx核心技术》第11章:实现MySQL数据库的负载均衡
后端·nginx·架构
weixin_436525071 小时前
SpringBoot 单体服务集成 Zipkin 实现链路追踪
java·spring boot·后端
q***78371 小时前
【玩转全栈】----Django制作部门管理页面
后端·python·django
Yeats_Liao2 小时前
时序数据库系列(八):InfluxDB配合Grafana可视化
数据库·后端·grafana·时序数据库
q***7483 小时前
Spring Boot环境配置
java·spring boot·后端
郝开3 小时前
Spring Boot 2.7.18(最终 2.x 系列版本)3 - 枚举规范定义:定义基础枚举接口;定义枚举工具类;示例枚举
spring boot·后端·python·枚举·enum
q***7483 小时前
Spring Boot 3.x 系列【3】Spring Initializr快速创建Spring Boot项目
spring boot·后端·spring
q***18063 小时前
十八,Spring Boot 整合 MyBatis-Plus 的详细配置
spring boot·后端·mybatis
m0_736927043 小时前
2025高频Java后端场景题汇总(全年汇总版)
java·开发语言·经验分享·后端·面试·职场和发展·跳槽