Redis

关注公众号 jb51net

关闭
首页 > 数据库 > Redis > Redis客户端缓存

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

作者:风象南

客户端缓存是指在应用程序内存中维护一份Redis数据的本地副本,以减少网络请求次数,降低延迟,并减轻Redis服务器负担,本文将分享Redis客户端缓存的四种实现方式,大家可以参考一下

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<String, String> 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<String, Object> getCacheStats() {
        CacheStats stats = localCache.stats();
        Map<String, Object> 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服务器辅助的客户端缓存 (Server-Assisted Client-Side Caching)

技术原理

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

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

Redis提供了两种跟踪模式:

实现示例

使用Lettuce(Spring Boot Redis的默认客户端)实现服务器辅助的客户端缓存:

@Service
public class RedisTrackingCacheService {
    
    private final StatefulRedisConnection<String, String> connection;
    private final RedisCommands<String, String> commands;
    private final Map<String, String> localCache = new ConcurrentHashMap<>();
    private final Set<String> 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<Object> 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<Object> 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<Map.Entry<String, String>> it = localCache.entrySet().iterator();
                while (it.hasNext()) {
                    String key = it.next().getKey();
                    if (key.startsWith(prefix)) {
                        it.remove();
                        trackedKeys.remove(key);
                    }
                }
            }
        }
    }
    
    // 获取缓存统计信息
    public Map<String, Object> getCacheStats() {
        Map<String, Object> 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();
        }
    }
}

优缺点分析

优点

缺点

适用场景

最佳实践

方式三:基于过期时间的缓存失效策略 (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<String, String> dynamicCache = Caffeine.newBuilder()
                .expireAfterWrite(ttl)
                .build();
        
        return dynamicCache.get(key, k -> redisTemplate.opsForValue().get(k));
    }
    
    // 定期刷新缓存
    @Scheduled(fixedRate = 60000) // 每分钟执行
    public void refreshCache() {
        // 获取需要刷新的键列表
        List<String> keysToRefresh = getKeysToRefresh();
        
        for (String key : keysToRefresh) {
            // 触发重新加载,会调用被@Cacheable注解的方法
            this.get(key);
        }
    }
    
    private List<String> getKeysToRefresh() {
        // 实际应用中,可能从配置系统或特定的Redis set中获取
        return Arrays.asList("config:app", "config:features", "daily:stats");
    }
    
    // 使用二级缓存模式,对热点数据使用更长的TTL
    public String getWithTwoLevelCache(String key) {
        // 首先查询本地一级缓存(短TTL)
        Cache<String, String> l1Cache = Caffeine.newBuilder()
                .maximumSize(1000)
                .expireAfterWrite(Duration.ofSeconds(10))
                .build();
        
        String value = l1Cache.getIfPresent(key);
        if (value != null) {
            return value;
        }
        
        // 查询本地二级缓存(长TTL)
        Cache<String, String> 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;
    }
}

优缺点分析

优点

缺点

适用场景

最佳实践

方式四:基于发布/订阅的缓存失效通知 (Pub/Sub-based Cache Invalidation)

技术原理

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

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

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

实现示例

@Service
public class RedisPubSubCacheService {
    
    private final StringRedisTemplate redisTemplate;
    private final Map<String, String> 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<String, Object> invalidation = new ObjectMapper().readValue(
                    invalidationMessage, new TypeReference<Map<String, Object>>() {});
            
            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<String> 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<String, Object> 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<String, Object> getCacheStats() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("cacheSize", localCache.size());
        return stats;
    }
}

优缺点分析

优点

缺点

适用场景

最佳实践

性能对比与选择指南

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

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

选择指南

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

总结

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

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

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

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

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

您可能感兴趣的文章:
阅读全文