当前位置: 代码网 > it编程>数据库>Redis > Redis预防缓存穿透的6种策略

Redis预防缓存穿透的6种策略

2025年04月28日 Redis 我要评论
在高并发系统中,redis作为缓存中间件已成为标配,它能有效减轻数据库压力、提升系统响应速度。然而,缓存并非万能,在实际应用中我们常常面临一个严峻问题——缓存穿透。这种现象可能

在高并发系统中,redis作为缓存中间件已成为标配,它能有效减轻数据库压力、提升系统响应速度。然而,缓存并非万能,在实际应用中我们常常面临一个严峻问题——缓存穿透。

这种现象可能导致redis失效,使大量请求直接冲击数据库,造成系统性能急剧下降甚至宕机。

缓存穿透原理分析

什么是缓存穿透

缓存穿透是指查询一个根本不存在的数据,由于缓存不命中,请求会穿透缓存层直接访问数据库。这种情况下,数据库也无法查询到对应数据,因此无法将结果写入缓存,导致每次同类请求都会重复访问数据库。

典型场景与危害

client ---> redis(未命中) ---> database(查询无果) ---> 不更新缓存 ---> 循环重复

缓存穿透的主要危害:

  • 数据库压力激增:大量无效查询直接落到数据库
  • 系统响应变慢:数据库负载过高导致整体性能下降
  • 资源浪费:无谓的查询消耗cpu和io资源
  • 安全风险:可能被恶意利用作为拒绝服务攻击的手段

缓存穿透通常有两种情况:

  • 正常业务查询:查询的数据确实不存在
  • 恶意攻击:故意构造不存在的key进行大量请求

下面介绍六种有效的防范策略。

策略一:空值缓存

原理

空值缓存是最简单直接的防穿透策略。当数据库查询不到某个key对应的值时,我们仍然将这个"空结果"缓存起来(通常以null值或特定标记表示),并设置一个相对较短的过期时间。这样,下次请求同一个不存在的key时,可以直接从缓存返回"空结果",避免再次查询数据库。

实现示例

@service
public class userserviceimpl implements userservice {
    
    @autowired
    private stringredistemplate redistemplate;
    
    @autowired
    private usermapper usermapper;
    
    private static final string key_prefix = "user:";
    private static final string empty_value = "{}";  // 空值标记
    private static final long empty_value_expire_seconds = 300;  // 空值过期时间
    private static final long normal_expire_seconds = 3600;  // 正常值过期时间
    
    @override
    public user getuserbyid(long userid) {
        string rediskey = key_prefix + userid;
        
        // 1. 查询缓存
        string userjson = redistemplate.opsforvalue().get(rediskey);
        
        // 2. 缓存命中
        if (userjson != null) {
            // 判断是否为空值
            if (empty_value.equals(userjson)) {
                return null;  // 返回空结果
            }
            // 正常缓存,反序列化并返回
            return json.parseobject(userjson, user.class);
        }
        
        // 3. 缓存未命中,查询数据库
        user user = usermapper.selectbyid(userid);
        
        // 4. 写入缓存
        if (user != null) {
            // 数据库查到数据,写入正常缓存
            redistemplate.opsforvalue().set(rediskey, 
                                           json.tojsonstring(user), 
                                           normal_expire_seconds, 
                                           timeunit.seconds);
        } else {
            // 数据库未查到数据,写入空值缓存
            redistemplate.opsforvalue().set(rediskey, 
                                           empty_value, 
                                           empty_value_expire_seconds, 
                                           timeunit.seconds);
        }
        
        return user;
    }
}

优缺点分析

优点

  • 实现简单,无需额外组件
  • 对系统侵入性低
  • 立竿见影的效果

缺点

  • 可能会占用较多的缓存空间
  • 如果空值较多,可能导致缓存效率下降
  • 无法应对大规模的恶意攻击
  • 短期内可能造成数据不一致(新增数据后缓存依然返回空值)

策略二:布隆过滤器

原理

布隆过滤器(bloom filter)是一种空间效率很高的概率型数据结构,用于检测一个元素是否属于一个集合。它的特点是存在误判,即可能会将不存在的元素误判为存在(false positive),但不会将存在的元素误判为不存在(false negative)。

布隆过滤器包含一个很长的二进制向量和一系列哈希函数。当插入一个元素时,使用各个哈希函数计算该元素的哈希值,并将二进制向量中相应位置置为1。查询时,同样计算哈希值并检查向量中对应位置,如果有任一位为0,则元素必定不存在;如果全部位都为1,则元素可能存在。

实现示例

使用redis的布隆过滤器模块(redis 4.0+支持模块扩展,需安装redisbloom):

@service
public class productservicewithbloomfilter implements productservice {
    
    @autowired
    private stringredistemplate redistemplate;
    
    @autowired
    private productmapper productmapper;
    
    private static final string bloom_filter_name = "product_filter";
    private static final string cache_key_prefix = "product:";
    private static final long cache_expire_seconds = 3600;
    
    // 初始化布隆过滤器,可在应用启动时执行
    @postconstruct
    public void initbloomfilter() {
        // 判断布隆过滤器是否存在
        boolean exists = (boolean) redistemplate.execute((rediscallback<boolean>) connection -> 
            connection.exists(bloom_filter_name.getbytes()));
        
        if (boolean.false.equals(exists)) {
            // 创建布隆过滤器,预计元素量为100万,错误率为0.01
            redistemplate.execute((rediscallback<object>) connection -> 
                connection.execute("bf.reserve", 
                                  bloom_filter_name.getbytes(), 
                                  "0.01".getbytes(), 
                                  "1000000".getbytes()));
            
            // 加载所有商品id到布隆过滤器
            list<long> allproductids = productmapper.getallproductids();
            for (long id : allproductids) {
                redistemplate.execute((rediscallback<boolean>) connection -> 
                    connection.execute("bf.add", 
                                      bloom_filter_name.getbytes(), 
                                      id.tostring().getbytes()) != 0);
            }
        }
    }
    
    @override
    public product getproductbyid(long productid) {
        string cachekey = cache_key_prefix + productid;
        
        // 1. 使用布隆过滤器检查id是否存在
        boolean mayexist = (boolean) redistemplate.execute((rediscallback<boolean>) connection -> 
            connection.execute("bf.exists", 
                             bloom_filter_name.getbytes(), 
                             productid.tostring().getbytes()) != 0);
        
        // 如果布隆过滤器判断不存在,则直接返回
        if (boolean.false.equals(mayexist)) {
            return null;
        }
        
        // 2. 查询缓存
        string productjson = redistemplate.opsforvalue().get(cachekey);
        if (productjson != null) {
            return json.parseobject(productjson, product.class);
        }
        
        // 3. 查询数据库
        product product = productmapper.selectbyid(productid);
        
        // 4. 更新缓存
        if (product != null) {
            redistemplate.opsforvalue().set(cachekey, 
                                           json.tojsonstring(product), 
                                           cache_expire_seconds, 
                                           timeunit.seconds);
        } else {
            // 布隆过滤器误判,数据库中不存在该商品
            // 可以考虑记录这类误判情况,优化布隆过滤器参数
            log.warn("bloom filter false positive for productid: {}", productid);
        }
        
        return product;
    }
    
    // 当新增商品时,需要将id添加到布隆过滤器
    public void addproducttobloomfilter(long productid) {
        redistemplate.execute((rediscallback<boolean>) connection -> 
            connection.execute("bf.add", 
                             bloom_filter_name.getbytes(), 
                             productid.tostring().getbytes()) != 0);
    }
}

优缺点分析

优点

  • 空间效率高,内存占用小
  • 查询速度快,时间复杂度o(k),k为哈希函数个数
  • 可以有效过滤大部分不存在的id查询
  • 可以与其他策略组合使用

缺点

  • 存在误判可能(false positive)
  • 无法从布隆过滤器中删除元素(标准实现)
  • 需要预先加载所有数据id,不适合动态变化频繁的场景
  • 实现相对复杂,需要额外维护布隆过滤器
  • 可能需要定期重建以适应数据变化

策略三:请求参数校验

原理

请求参数校验是一种在业务层面防止缓存穿透的手段。通过对请求参数进行合法性校验,过滤掉明显不合理的请求,避免这些请求到达缓存和数据库层。这种方法特别适合防范恶意攻击。

实现示例

@restcontroller
@requestmapping("/api/user")
public class usercontroller {
    
    @autowired
    private userservice userservice;
    
    @getmapping("/{userid}")
    public responseentity<?> getuserbyid(@pathvariable string userid) {
        // 1. 基本格式校验
        if (!userid.matches("\d+")) {
            return responseentity.badrequest().body("userid must be numeric");
        }
        
        // 2. 基本逻辑校验
        long id = long.parselong(userid);
        if (id <= 0 || id > 100000000) {  // 假设id范围限制
            return responseentity.badrequest().body("userid out of valid range");
        }
        
        // 3. 调用业务服务
        user user = userservice.getuserbyid(id);
        if (user == null) {
            return responseentity.notfound().build();
        }
        
        return responseentity.ok(user);
    }
}

在服务层也可以增加参数检验:

@service
public class userserviceimpl implements userservice {
    
    // 白名单,只允许查询这些id前缀(举例)
    private static final set<string> id_prefixes = set.of("100", "200", "300");
    
    @override
    public user getuserbyid(long userid) {
        // 更复杂的业务规则校验
        string idstr = userid.tostring();
        boolean valid = false;
        
        for (string prefix : id_prefixes) {
            if (idstr.startswith(prefix)) {
                valid = true;
                break;
            }
        }
        
        if (!valid) {
            log.warn("attempt to access invalid user id pattern: {}", userid);
            return null;
        }
        
        // 正常业务逻辑...
        return getuserfromcacheordb(userid);
    }
}

优缺点分析

优点

  • 实现简单,无需额外组件
  • 能在请求早期拦截明显不合理的访问
  • 可以结合业务规则进行精细化控制
  • 减轻系统整体负担

缺点

  • 无法覆盖所有非法请求场景
  • 需要对业务非常了解,才能设计合理的校验规则
  • 可能引入复杂的业务逻辑
  • 校验过于严格可能影响正常用户体验

策略四:接口限流与熔断

原理

限流是控制系统访问频率的有效手段,可以防止突发流量对系统造成冲击。熔断则是在系统负载过高时,暂时拒绝部分请求以保护系统。这两种机制结合使用,可以有效防范缓存穿透带来的系统风险。

实现示例

使用springboot+resilience4j实现限流和熔断:

@configuration
public class resilienceconfig {
    
    @bean
    public ratelimiterregistry ratelimiterregistry() {
        ratelimiterconfig config = ratelimiterconfig.custom()
            .limitrefreshperiod(duration.ofseconds(1))
            .limitforperiod(100)  // 每秒允许100个请求
            .timeoutduration(duration.ofmillis(25))
            .build();
        
        return ratelimiterregistry.of(config);
    }
    
    @bean
    public circuitbreakerregistry circuitbreakerregistry() {
        circuitbreakerconfig config = circuitbreakerconfig.custom()
            .failureratethreshold(50)  // 50%失败率触发熔断
            .slidingwindowsize(100)    // 基于最近100次调用
            .minimumnumberofcalls(10)  // 至少10次调用才会触发熔断
            .waitdurationinopenstate(duration.ofseconds(10)) // 熔断后等待时间
            .build();
        
        return circuitbreakerregistry.of(config);
    }
}

@service
public class productservicewithresilience {

    private final productmapper productmapper;
    private final stringredistemplate redistemplate;
    private final ratelimiter ratelimiter;
    private final circuitbreaker circuitbreaker;
    
    public productservicewithresilience(
            productmapper productmapper,
            stringredistemplate redistemplate,
            ratelimiterregistry ratelimiterregistry,
            circuitbreakerregistry circuitbreakerregistry) {
        this.productmapper = productmapper;
        this.redistemplate = redistemplate;
        this.ratelimiter = ratelimiterregistry.ratelimiter("productservice");
        this.circuitbreaker = circuitbreakerregistry.circuitbreaker("productservice");
    }
    
    public product getproductbyid(long productid) {
        // 1. 应用限流器
        return ratelimiter.executesupplier(() -> {
            // 2. 应用熔断器
            return circuitbreaker.executesupplier(() -> {
                return dogetproduct(productid);
            });
        });
    }
    
    private product dogetproduct(long productid) {
        string cachekey = "product:" + productid;
        
        // 查询缓存
        string productjson = redistemplate.opsforvalue().get(cachekey);
        if (productjson != null) {
            return json.parseobject(productjson, product.class);
        }
        
        // 查询数据库
        product product = productmapper.selectbyid(productid);
        
        // 更新缓存
        if (product != null) {
            redistemplate.opsforvalue().set(cachekey, json.tojsonstring(product), 1, timeunit.hours);
        } else {
            // 空值缓存,短期有效
            redistemplate.opsforvalue().set(cachekey, "", 5, timeunit.minutes);
        }
        
        return product;
    }
    
    // 熔断后的降级方法
    private product fallbackmethod(long productid, throwable t) {
        log.warn("circuit breaker triggered for productid: {}", productid, t);
        // 返回默认商品或者从本地缓存获取
        return new product(productid, "temporary unavailable", 0.0);
    }
}

优缺点分析

优点

  • 提供系统级别的保护
  • 能有效应对突发流量和恶意攻击
  • 保障系统稳定性和可用性
  • 可以结合监控系统进行动态调整

缺点

  • 可能影响正常用户体验
  • 配置调优有一定难度
  • 需要完善的降级策略
  • 无法彻底解决缓存穿透问题,只是减轻其影响

策略五:缓存预热

原理

缓存预热是指在系统启动或特定时间点,提前将可能被查询的数据加载到缓存中,避免用户请求时因缓存不命中而导致的数据库访问。对于缓存穿透问题,预热可以提前将有效数据的空间占满,减少直接查询数据库的可能性。

实现示例

@component
public class cachewarmuptask {
    
    @autowired
    private productmapper productmapper;
    
    @autowired
    private stringredistemplate redistemplate;
    
    @autowired
    private redisbloomfilter bloomfilter;
    
    // 系统启动时执行缓存预热
    @postconstruct
    public void warmupcacheonstartup() {
        // 异步执行预热任务,避免阻塞应用启动
        completablefuture.runasync(this::warmuphotproducts);
    }
    
    // 每天凌晨2点刷新热门商品缓存
    @scheduled(cron = "0 0 2 * * ?")
    public void scheduledwarmup() {
        warmuphotproducts();
    }
    
    private void warmuphotproducts() {
        log.info("开始预热商品缓存...");
        long starttime = system.currenttimemillis();
        
        try {
            // 1. 获取热门商品列表(例如销量top5000)
            list<product> hotproducts = productmapper.findhotproducts(5000);
            
            // 2. 更新缓存和布隆过滤器
            for (product product : hotproducts) {
                string cachekey = "product:" + product.getid();
                redistemplate.opsforvalue().set(
                    cachekey, 
                    json.tojsonstring(product), 
                    6, timeunit.hours
                );
                
                // 更新布隆过滤器
                bloomfilter.add("product_filter", product.getid().tostring());
            }
            
            // 3. 同时预热一些必要的聚合信息
            list<category> categories = productmapper.findallcategories();
            for (category category : categories) {
                string cachekey = "category:" + category.getid();
                list<long> productids = productmapper.findproductidsbycategory(category.getid());
                redistemplate.opsforvalue().set(
                    cachekey,
                    json.tojsonstring(productids),
                    12, timeunit.hours
                );
            }
            
            long duration = system.currenttimemillis() - starttime;
            log.info("缓存预热完成,耗时:{}ms,预热商品数量:{}", duration, hotproducts.size());
            
        } catch (exception e) {
            log.error("缓存预热失败", e);
        }
    }
}

优缺点分析

优点

  • 提高系统启动后的访问性能
  • 减少缓存冷启动问题
  • 可以定时刷新,保持数据鲜度
  • 避免用户等待

缺点

  • 无法覆盖所有可能的数据访问
  • 占用额外的系统资源
  • 对冷门数据无效
  • 需要合理选择预热数据范围,避免资源浪费

策略六:分级过滤策略

原理

分级过滤策略是将多种防穿透措施组合使用,形成多层防护网。通过在不同层次设置过滤条件,既能保证系统性能,又能最大限度地防止缓存穿透。一个典型的分级过滤策略包括:前端过滤 -> api网关过滤 -> 应用层过滤 -> 缓存层过滤 -> 数据库保护。

实现示例

以下是一个多层防护的综合示例:

// 1. 网关层过滤(使用spring cloud gateway)
@configuration
public class gatewayfilterconfig {
    
    @bean
    public routelocator customroutelocator(routelocatorbuilder builder) {
        return builder.routes()
            .route("product_route", r -> r.path("/api/product/**")
                // 路径格式验证
                .and().predicate(exchange -> {
                    string path = exchange.getrequest().geturi().getpath();
                    // 检查product/{id}路径,确保id为数字
                    if (path.matches("/api/product/\d+")) {
                        string id = path.substring(path.lastindexof('/') + 1);
                        long productid = long.parselong(id);
                        return productid > 0 && productid < 10000000; // 合理范围检查
                    }
                    return true;
                })
                // 限流过滤
                .filters(f -> f.requestratelimiter()
                    .ratelimiter(redisratelimiter.class, c -> c.setreplenishrate(10).setburstcapacity(20))
                    .and()
                    .circuitbreaker(c -> c.setname("productcb").setfallbackuri("forward:/fallback"))
                )
                .uri("lb://product-service")
            )
            .build();
    }
}

// 2. 应用层过滤(resilience4j + bloom filter)
@service
public class productserviceimpl implements productservice {
    
    private final stringredistemplate redistemplate;
    private final productmapper productmapper;
    private final bloomfilter<string> localbloomfilter;
    private final ratelimiter ratelimiter;
    private final circuitbreaker circuitbreaker;
    
    @value("${cache.product.expire-seconds:3600}")
    private int cacheexpireseconds;
    
    // 构造函数注入...
    
    @postconstruct
    public void initlocalfilter() {
        // 创建本地布隆过滤器作为二级保护
        localbloomfilter = bloomfilter.create(
            funnels.stringfunnel(standardcharsets.utf_8),
            1000000,  // 预期元素数量
            0.001     // 误判率
        );
        
        // 初始化本地布隆过滤器数据
        list<string> allproductids = productmapper.getallproductidsasstring();
        for (string id : allproductids) {
            localbloomfilter.put(id);
        }
    }
    
    @override
    public product getproductbyid(long productid) {
        string productidstr = productid.tostring();
        
        // 1. 本地布隆过滤器预检
        if (!localbloomfilter.mightcontain(productidstr)) {
            log.info("product filtered by local bloom filter: {}", productid);
            return null;
        }
        
        // 2. redis布隆过滤器二次检查
        boolean mayexist = redistemplate.execute(
            (rediscallback<boolean>) connection -> connection.execute(
                "bf.exists", 
                "product_filter".getbytes(), 
                productidstr.getbytes()
            ) != 0
        );
        
        if (boolean.false.equals(mayexist)) {
            log.info("product filtered by redis bloom filter: {}", productid);
            return null;
        }
        
        // 3. 应用限流和熔断保护
        try {
            return ratelimiter.executesupplier(() -> 
                circuitbreaker.executesupplier(() -> {
                    return getproductfromcacheordb(productid);
                })
            );
        } catch (requestnotpermitted e) {
            log.warn("request rate limited for product: {}", productid);
            throw new serviceexception("service is busy, please try again later");
        } catch (callnotpermittedexception e) {
            log.warn("circuit breaker open for product queries");
            throw new serviceexception("service is temporarily unavailable");
        }
    }
    
    private product getproductfromcacheordb(long productid) {
        string cachekey = "product:" + productid;
        
        // 4. 查询缓存
        string cachedvalue = redistemplate.opsforvalue().get(cachekey);
        
        if (cachedvalue != null) {
            // 处理空值缓存情况
            if (cachedvalue.isempty()) {
                return null;
            }
            return json.parseobject(cachedvalue, product.class);
        }
        
        // 5. 查询数据库(加入db保护)
        product product = null;
        try {
            product = productmapper.selectbyid(productid);
        } catch (exception e) {
            log.error("database error when querying product: {}", productid, e);
            throw new serviceexception("system error, please try again later");
        }
        
        // 6. 更新缓存(空值也缓存)
        if (product != null) {
            redistemplate.opsforvalue().set(
                cachekey, 
                json.tojsonstring(product),
                cacheexpireseconds,
                timeunit.seconds
            );
            
            // 确保布隆过滤器包含此id
            redistemplate.execute(
                (rediscallback<boolean>) connection -> connection.execute(
                    "bf.add", 
                    "product_filter".getbytes(), 
                    productid.tostring().getbytes()
                ) != 0
            );
            
            localbloomfilter.put(productid.tostring());
        } else {
            // 缓存空值,短时间过期
            redistemplate.opsforvalue().set(
                cachekey,
                "",
                60, // 空值短期缓存
                timeunit.seconds
            );
        }
        
        return product;
    }
}

优缺点分析

优点

  • 提供全方位的系统保护
  • 各层防护互为补充,形成完整防线
  • 可以灵活配置各层策略
  • 最大限度减少资源浪费和性能损耗

缺点

  • 实现复杂度高
  • 各层配置需要协调一致
  • 可能增加系统响应时间
  • 维护成本相对较高

总结

防范缓存穿透不仅是技术问题,更是系统设计和运维的重要环节。

在实际应用中,应根据具体业务场景和系统规模选择合适的策略组合。通常,单一策略难以完全解决问题,而组合策略能够提供更全面的防护。无论采用何种策略,定期监控和性能评估都是保障缓存系统高效运行的必要手段。

到此这篇关于redis预防缓存穿透的6种策略的文章就介绍到这了,更多相关redis缓存穿透内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com