Redis实现客户端缓存的4种方式

redis作为当今最流行的内存数据库和缓存系统,被广泛应用于各类应用场景。然而,即使redis本身性能卓越,在高并发场景下,应用与redis服务器之间的网络通信仍可能成为性能瓶颈。

这时,客户端缓存技术便显得尤为重要。

客户端缓存是指在应用程序内存中维护一份redis数据的本地副本,以减少网络请求次数,降低延迟,并减轻redis服务器负担。

本文将分享redis客户端缓存的四种实现方式,分析其原理、优缺点、适用场景及最佳实践.

方式一:本地内存缓存 (local in-memory cache)

技术原理

本地内存缓存是最直接的客户端缓存实现方式,它在应用程序内存中使用数据结构(如hashmap、concurrenthashmap或专业缓存库如caffeine、guava cache等)存储从redis获取的数据。这种方式完全由应用程序自己管理,与redis服务器无关。

实现示例

以下是使用spring boot和caffeine实现的简单本地缓存示例:

@service
public class redislocalcacheservice {
    
    private final stringredistemplate redistemplate;
    private final cache localcache;
    
    public redislocalcacheservice(stringredistemplate redistemplate) {
        this.redistemplate = redistemplate;
        
        // 配置caffeine缓存
        this.localcache = caffeine.newbuilder()
                .maximumsize(10_000)  // 最大缓存条目数
                .expireafterwrite(duration.ofminutes(5))  // 写入后过期时间
                .recordstats()  // 记录统计信息
                .build();
    }
    
    public string get(string key) {
        // 首先尝试从本地缓存获取
        string value = localcache.getifpresent(key);
        
        if (value != null) {
            // 本地缓存命中
            return value;
        }
        
        // 本地缓存未命中,从redis获取
        value = redistemplate.opsforvalue().get(key);
        
        if (value != null) {
            // 将从redis获取的值放入本地缓存
            localcache.put(key, value);
        }
        
        return value;
    }
    
    public void set(string key, string value) {
        // 更新redis
        redistemplate.opsforvalue().set(key, value);
        
        // 更新本地缓存
        localcache.put(key, value);
    }
    
    public void delete(string key) {
        // 从redis中删除
        redistemplate.delete(key);
        
        // 从本地缓存中删除
        localcache.invalidate(key);
    }
    
    // 获取缓存统计信息
    public map getcachestats() {
        cachestats stats = localcache.stats();
        map statsmap = new hashmap<>();
        
        statsmap.put("hitcount", stats.hitcount());
        statsmap.put("misscount", stats.misscount());
        statsmap.put("hitrate", stats.hitrate());
        statsmap.put("evictioncount", stats.evictioncount());
        
        return statsmap;
    }
}

优缺点分析

优点

  • 实现简单,易于集成
  • 无需额外的服务器支持
  • 可完全控制缓存行为(大小、过期策略等)
  • 显著减少网络请求次数
  • 对redis服务器完全透明

缺点

  • 缓存一致性问题:当redis数据被其他应用或服务更新时,本地缓存无法感知变化
  • 内存占用:需要消耗应用程序的内存资源
  • 冷启动问题:应用重启后缓存需要重新预热
  • 分布式环境下多实例之间的缓存不一致

适用场景

  • 读多写少的数据(如配置信息、静态数据)
  • 对数据实时性要求不高的场景
  • 单体应用或数据一致性要求不高的分布式系统
  • 作为其他缓存策略的补充手段

最佳实践

  • 合理设置缓存大小和过期时间:避免过多内存占用
  • 选择正确的缓存驱逐策略:lru、lfu等根据业务特点选择
  • 定期刷新重要数据:主动更新而不总是被动等待过期
  • 添加监控和统计:跟踪命中率、内存使用等指标
  • 考虑缓存预热:应用启动时主动加载常用数据

方式二:redis服务器辅助的客户端缓存 (server-assisted client-side caching)

技术原理

redis 6.0引入了服务器辅助的客户端缓存功能,也称为跟踪模式(tracking)。

在这种模式下,redis服务器会跟踪客户端请求的键,当这些键被修改时,服务器会向客户端发送失效通知。这种机制确保了客户端缓存与redis服务器之间的数据一致性。

redis提供了两种跟踪模式:

  • 默认模式:服务器精确跟踪每个客户端关注的键
  • 广播模式:服务器广播所有键的变更,客户端过滤自己关心的键

实现示例

使用lettuce(spring boot redis的默认客户端)实现服务器辅助的客户端缓存:

@service
public class redistrackingcacheservice {
    
    private final statefulredisconnection connection;
    private final rediscommands commands;
    private final map localcache = new concurrenthashmap<>();
    private final set trackedkeys = concurrenthashmap.newkeyset();
    
    public redistrackingcacheservice(redisclient redisclient) {
        this.connection = redisclient.connect();
        this.commands = connection.sync();
        
        // 配置客户端缓存失效监听器
        connection.addlistener(message -> {
            if (message instanceof pushmessage) {
                pushmessage pushmessage = (pushmessage) message;
                if ("invalidate".equals(pushmessage.gettype())) {
                    list invalidations = pushmessage.getcontent();
                    handleinvalidations(invalidations);
                }
            }
        });
        
        // 启用客户端缓存跟踪
        commands.clienttracking(clienttrackingargs.builder.enabled());
    }
    
    public string get(string key) {
        // 首先尝试从本地缓存获取
        string value = localcache.get(key);
        
        if (value != null) {
            return value;
        }
        
        // 本地缓存未命中,从redis获取
        value = commands.get(key);
        
        if (value != null) {
            // 启用跟踪后,redis服务器会记录这个客户端正在跟踪这个键
            localcache.put(key, value);
            trackedkeys.add(key);
        }
        
        return value;
    }
    
    public void set(string key, string value) {
        // 更新redis
        commands.set(key, value);
        
        // 更新本地缓存
        localcache.put(key, value);
        trackedkeys.add(key);
    }
    
    private void handleinvalidations(list invalidations) {
        if (invalidations != null && invalidations.size() >= 2) {
            // 解析失效消息
            string invalidationtype = new string((byte[]) invalidations.get(0));
            
            if ("key".equals(invalidationtype)) {
                // 单个键失效
                string invalidatedkey = new string((byte[]) invalidations.get(1));
                localcache.remove(invalidatedkey);
                trackedkeys.remove(invalidatedkey);
            } else if ("prefix".equals(invalidationtype)) {
                // 前缀失效
                string prefix = new string((byte[]) invalidations.get(1));
                iterator> it = localcache.entryset().iterator();
                while (it.hasnext()) {
                    string key = it.next().getkey();
                    if (key.startswith(prefix)) {
                        it.remove();
                        trackedkeys.remove(key);
                    }
                }
            }
        }
    }
    
    // 获取缓存统计信息
    public map getcachestats() {
        map stats = new hashmap<>();
        stats.put("cachesize", localcache.size());
        stats.put("trackedkeys", trackedkeys.size());
        return stats;
    }
    
    // 清除本地缓存但保持跟踪
    public void clearlocalcache() {
        localcache.clear();
    }
    
    // 关闭连接并清理资源
    @predestroy
    public void cleanup() {
        if (connection != null) {
            connection.close();
        }
    }
}

优缺点分析

优点

  • 自动维护缓存一致性,无需手动同步
  • redis服务器能感知客户端缓存状态
  • 显著减少网络请求数量
  • 支持细粒度(键级别)的缓存控制
  • 实时感知数据变更,数据一致性保证强

缺点

  • 需要redis 6.0以上版本支持
  • 增加redis服务器内存占用(跟踪状态)
  • 客户端连接必须保持活跃
  • 服务器广播模式可能产生大量失效消息
  • 实现复杂度高于简单本地缓存

适用场景

  • 对数据一致性要求高的场景
  • 读多写少但又需要实时反映写入变化的场景
  • 分布式系统中多客户端访问相同数据集
  • 大型应用需要减轻redis负载但又不能容忍数据不一致

最佳实践

  • 选择合适的跟踪模式

    • 默认模式:客户端数量少且各自访问不同数据集
    • 广播模式:客户端数量多或访问模式不可预测
  • 使用前缀跟踪:按键前缀组织数据并跟踪,减少跟踪开销

  • 合理设置redirect参数:在多个客户端共享跟踪连接时

  • 主动重连策略:连接断开后尽快重建连接和缓存

  • 设置合理的本地缓存大小:避免过度占用应用内存

方式三:基于过期时间的缓存失效策略 (ttl-based cache invalidation)

技术原理

基于过期时间(time-to-live,ttl)的缓存失效策略是一种简单有效的客户端缓存方案。

它为本地缓存中的每个条目设置一个过期时间,过期后自动删除或刷新。

这种方式不依赖服务器通知,而是通过预设的时间窗口来控制缓存的新鲜度,平衡了数据一致性和系统复杂度。

实现示例

使用spring cache和caffeine实现ttl缓存:

@configuration
public class cacheconfig {
    
    @bean
    public cachemanager cachemanager() {
        caffeinecachemanager cachemanager = new caffeinecachemanager();
        cachemanager.setcaffeinespec(caffeinespec.parse(
                "maximumsize=10000,expireafterwrite=300s,recordstats"));
        return cachemanager;
    }
}

@service
public class redisttlcacheservice {
    
    private final stringredistemplate redistemplate;
    
    @autowired
    public redisttlcacheservice(stringredistemplate redistemplate) {
        this.redistemplate = redistemplate;
    }
    
    @cacheable(value = "rediscache", key = "#key")
    public string get(string key) {
        return redistemplate.opsforvalue().get(key);
    }
    
    @cacheput(value = "rediscache", key = "#key")
    public string set(string key, string value) {
        redistemplate.opsforvalue().set(key, value);
        return value;
    }
    
    @cacheevict(value = "rediscache", key = "#key")
    public void delete(string key) {
        redistemplate.delete(key);
    }
    
    // 分层缓存 - 不同过期时间的缓存
    @cacheable(value = "shorttermcache", key = "#key")
    public string getwithshortttl(string key) {
        return redistemplate.opsforvalue().get(key);
    }
    
    @cacheable(value = "longtermcache", key = "#key")
    public string getwithlongttl(string key) {
        return redistemplate.opsforvalue().get(key);
    }
    
    // 在程序逻辑中手动控制过期时间
    public string getwithdynamicttl(string key, duration ttl) {
        // 使用loadingcache,可以动态设置过期时间
        cache dynamiccache = caffeine.newbuilder()
                .expireafterwrite(ttl)
                .build();
        
        return dynamiccache.get(key, k -> redistemplate.opsforvalue().get(k));
    }
    
    // 定期刷新缓存
    @scheduled(fixedrate = 60000) // 每分钟执行
    public void refreshcache() {
        // 获取需要刷新的键列表
        list keystorefresh = getkeystorefresh();
        
        for (string key : keystorefresh) {
            // 触发重新加载,会调用被@cacheable注解的方法
            this.get(key);
        }
    }
    
    private list getkeystorefresh() {
        // 实际应用中,可能从配置系统或特定的redis set中获取
        return arrays.aslist("config:app", "config:features", "daily:stats");
    }
    
    // 使用二级缓存模式,对热点数据使用更长的ttl
    public string getwithtwolevelcache(string key) {
        // 首先查询本地一级缓存(短ttl)
        cache l1cache = caffeine.newbuilder()
                .maximumsize(1000)
                .expireafterwrite(duration.ofseconds(10))
                .build();
        
        string value = l1cache.getifpresent(key);
        if (value != null) {
            return value;
        }
        
        // 查询本地二级缓存(长ttl)
        cache l2cache = caffeine.newbuilder()
                .maximumsize(10000)
                .expireafterwrite(duration.ofminutes(5))
                .build();
        
        value = l2cache.getifpresent(key);
        if (value != null) {
            // 提升到一级缓存
            l1cache.put(key, value);
            return value;
        }
        
        // 查询redis
        value = redistemplate.opsforvalue().get(key);
        if (value != null) {
            // 更新两级缓存
            l1cache.put(key, value);
            l2cache.put(key, value);
        }
        
        return value;
    }
}

优缺点分析

优点

  • 实现简单,易于集成到现有系统
  • 不依赖redis服务器特殊功能
  • 适用于任何redis版本
  • 内存占用可控,过期的缓存会自动清理
  • 通过调整ttl可以在一致性和性能之间取得平衡

缺点

  • 无法立即感知数据变更,存在一致性窗口期
  • ttl设置过短会导致缓存效果不佳
  • ttl设置过长会增加数据不一致的风险
  • 所有键使用统一ttl策略时缺乏灵活性
  • 可能出现"缓存风暴"(大量缓存同时过期导致突发流量)

适用场景

  • 可以容忍短时间数据不一致的应用
  • 读多写少的数据访问模式
  • 更新频率相对可预测的数据
  • 使用旧数据造成的影响较小的场景
  • 简单应用或作为其他缓存策略的补充

最佳实践

  • 基于数据特性设置不同ttl

    • 频繁变化的数据:短ttl
    • 相对稳定的数据:长ttl
  • 添加随机因子:ttl加上随机偏移量,避免缓存同时过期

  • 实现缓存预热机制:应用启动时主动加载热点数据

  • 结合后台刷新:对关键数据使用定时任务在过期前主动刷新

  • 监控缓存效率:跟踪命中率、过期率等指标,动态调整ttl策略

方式四:基于发布/订阅的缓存失效通知 (pub/sub-based cache invalidation)

技术原理

基于发布/订阅(pub/sub)的缓存失效通知利用redis的发布/订阅功能来协调分布式系统中的缓存一致性。

当数据发生变更时,应用程序通过redis发布一条失效消息到特定频道,所有订阅该频道的客户端收到消息后清除对应的本地缓存。

这种方式实现了主动的缓存失效通知,而不依赖于redis 6.0以上版本的跟踪功能。

实现示例

@service
public class redispubsubcacheservice {
    
    private final stringredistemplate redistemplate;
    private final map localcache = new concurrenthashmap<>();
    
    @autowired
    public redispubsubcacheservice(stringredistemplate redistemplate) {
        this.redistemplate = redistemplate;
        
        // 订阅缓存失效通知
        subscribetoinvalidations();
    }
    
    private void subscribetoinvalidations() {
        // 使用独立的redis连接订阅缓存失效通知
        redisconnectionfactory connectionfactory = redistemplate.getconnectionfactory();
        
        if (connectionfactory != null) {
            // 创建消息监听容器
            redismessagelistenercontainer container = new redismessagelistenercontainer();
            container.setconnectionfactory(connectionfactory);
            
            // 消息监听器,处理缓存失效通知
            messagelistener invalidationlistener = (message, pattern) -> {
                string invalidationmessage = new string(message.getbody());
                handlecacheinvalidation(invalidationmessage);
            };
            
            // 订阅缓存失效通知频道
            container.addmessagelistener(invalidationlistener, new patterntopic("cache:invalidations"));
            container.start();
        }
    }
    
    private void handlecacheinvalidation(string invalidationmessage) {
        try {
            // 解析失效消息
            map invalidation = new objectmapper().readvalue(
                    invalidationmessage, new typereference>() {});
            
            string type = (string) invalidation.get("type");
            
            if ("key".equals(type)) {
                // 单个键失效
                string key = (string) invalidation.get("key");
                localcache.remove(key);
            } else if ("prefix".equals(type)) {
                // 前缀失效
                string prefix = (string) invalidation.get("prefix");
                localcache.keyset().removeif(key -> key.startswith(prefix));
            } else if ("all".equals(type)) {
                // 清空整个缓存
                localcache.clear();
            }
        } catch (exception e) {
            // 处理解析错误
        }
    }
    
    public string get(string key) {
        // 首先尝试从本地缓存获取
        string value = localcache.get(key);
        
        if (value != null) {
            return value;
        }
        
        // 本地缓存未命中,从redis获取
        value = redistemplate.opsforvalue().get(key);
        
        if (value != null) {
            // 存入本地缓存
            localcache.put(key, value);
        }
        
        return value;
    }
    
    public void set(string key, string value) {
        // 更新redis
        redistemplate.opsforvalue().set(key, value);
        
        // 更新本地缓存
        localcache.put(key, value);
        
        // 发布缓存更新通知
        publishinvalidation("key", key);
    }
    
    public void delete(string key) {
        // 从redis中删除
        redistemplate.delete(key);
        
        // 从本地缓存中删除
        localcache.remove(key);
        
        // 发布缓存失效通知
        publishinvalidation("key", key);
    }
    
    public void deletebyprefix(string prefix) {
        // 获取并删除指定前缀的键
        set keys = redistemplate.keys(prefix + "*");
        if (keys != null && !keys.isempty()) {
            redistemplate.delete(keys);
        }
        
        // 清除本地缓存中匹配的键
        localcache.keyset().removeif(key -> key.startswith(prefix));
        
        // 发布前缀失效通知
        publishinvalidation("prefix", prefix);
    }
    
    public void clearallcache() {
        // 清空本地缓存
        localcache.clear();
        
        // 发布全局失效通知
        publishinvalidation("all", null);
    }
    
    private void publishinvalidation(string type, string key) {
        try {
            // 创建失效消息
            map invalidation = new hashmap<>();
            invalidation.put("type", type);
            if (key != null) {
                invalidation.put(type.equals("key") ? "key" : "prefix", key);
            }
            invalidation.put("timestamp", system.currenttimemillis());
            
            // 添加来源标识,防止自己接收自己发出的消息
            invalidation.put("source", getapplicationinstanceid());
            
            // 序列化并发布消息
            string message = new objectmapper().writevalueasstring(invalidation);
            redistemplate.convertandsend("cache:invalidations", message);
        } catch (exception e) {
            // 处理序列化错误
        }
    }
    
    private string getapplicationinstanceid() {
        // 返回应用实例唯一标识,避免处理自己发出的消息
        return "app-instance-" + uuid.randomuuid().tostring();
    }
    
    // 获取缓存统计信息
    public map getcachestats() {
        map stats = new hashmap<>();
        stats.put("cachesize", localcache.size());
        return stats;
    }
}

优缺点分析

优点

  • 不依赖redis特定版本的高级功能
  • 可实现近实时的缓存一致性
  • 适用于分布式系统中的多实例协调
  • 灵活度高,支持键级别、前缀级别和全局缓存操作
  • 可扩展为处理复杂的缓存依赖关系

缺点

  • 消息可能丢失,导致缓存不一致
  • 发布/订阅不保证消息持久化和有序交付
  • 系统复杂度增加,需要额外的消息处理逻辑
  • 实现不当可能导致消息风暴
  • 网络分区可能导致通知失败

适用场景

  • 多实例分布式应用需要协调缓存状态
  • 对缓存一致性有较高要求但又不想依赖redis 6.0+的跟踪功能
  • 需要实现跨服务缓存协调的系统
  • 微服务架构中的数据变更传播
  • 需要细粒度控制缓存失效的应用

最佳实践

  • 避免处理自己发出的消息:通过源标识过滤消息
  • 实现消息幂等处理:同一消息可能收到多次
  • 设置消息过期时间:忽略延迟过久的消息
  • 批量处理密集更新:合并短时间内的多次失效通知
  • 结合ttl策略:作为安全保障,设置最大缓存生命周期
  • 监控订阅连接:确保失效通知能正常接收
  • 考虑消息可靠性:关键场景可结合消息队列实现更可靠的通知

性能对比与选择指南

各种缓存策略的性能对比:

实现方式实时性复杂度内存占用网络开销一致性保证redis版本要求
本地内存缓存任意
服务器辅助缓存6.0+
ttl过期策略任意
pub/sub通知中强任意

选择指南

根据以下因素选择合适的缓存策略:

  • 数据一致性要求

    • 要求严格一致性:选择服务器辅助缓存
    • 允许短暂不一致:考虑ttl或pub/sub方案
    • 对一致性要求低:简单本地缓存足够
  • 应用架构

    • 单体应用:本地缓存或ttl方案简单有效
    • 微服务架构:pub/sub或服务器辅助缓存更合适
    • 高扩展性需求:避免纯本地缓存
  • redis版本

    • redis 6.0+:可考虑服务器辅助缓存
    • 旧版redis:使用其他三种方案
  • 读写比例

    • 高读低写:所有方案都适用
    • 写入频繁:慎用纯本地缓存,考虑ttl或服务器辅助方案
  • 资源限制

    • 内存受限:使用ttl控制缓存大小
    • 网络受限:优先考虑本地缓存
    • redis负载已高:本地缓存可减轻压力

总结

redis客户端缓存是提升应用性能的强大工具,通过减少网络请求和数据库访问,可以显著降低延迟并提高吞吐量。

在实际应用中,这些策略往往不是相互排斥的,而是可以组合使用,针对不同类型的数据采用不同的缓存策略,以获得最佳性能和数据一致性平衡。

无论选择哪种缓存策略,关键是理解自己应用的数据访问模式和一致性需求,并据此设计最合适的缓存解决方案。

通过正确应用客户端缓存技术,可以在保持数据一致性的同时,显著提升系统性能和用户体验。

到此这篇关于redis实现客户端缓存的4种方式的文章就介绍到这了,更多相关redis客户端缓存内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

发布于 2025-05-07 21:39:03
分享
海报
103
上一篇:如何彻底清除Windows系统中的2345软件? 下一篇:MySQL连接中断问题分析与解决方案
目录

    推荐阅读

    忘记密码?

    图形验证码