Redis作为当今最流行的内存数据库和缓存系统,被广泛应用于各类应用场景。然而,即使Redis本身性能卓越,在高并发场景下,应用与Redis服务器之间的网络通信仍可能成为性能瓶颈。
这时,客户端缓存技术便显得尤为重要。
客户端缓存是指在应用程序内存中维护一份Redis数据的本地副本,以减少网络请求次数,降低延迟,并减轻Redis服务器负担。
本文将分享Redis客户端缓存的四种实现方式,分析其原理、优缺点、适用场景及最佳实践.
本地内存缓存是最直接的客户端缓存实现方式,它在应用程序内存中使用数据结构(如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 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
优点
缺点
选择合适的跟踪模式:
使用前缀跟踪:按键前缀组织数据并跟踪,减少跟踪开销
合理设置REDIRECT参数:在多个客户端共享跟踪连接时
主动重连策略:连接断开后尽快重建连接和缓存
设置合理的本地缓存大小:避免过度占用应用内存
基于过期时间(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;
}
}
优点
缺点
基于数据特性设置不同TTL:
添加随机因子:TTL加上随机偏移量,避免缓存同时过期
实现缓存预热机制:应用启动时主动加载热点数据
结合后台刷新:对关键数据使用定时任务在过期前主动刷新
监控缓存效率:跟踪命中率、过期率等指标,动态调整TTL策略
基于发布/订阅(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
优点
缺点
各种缓存策略的性能对比:
实现方式 | 实时性 | 复杂度 | 内存占用 | 网络开销 | 一致性保证 | Redis版本要求 |
---|---|---|---|---|---|---|
本地内存缓存 | 低 | 低 | 高 | 低 | 弱 | 任意 |
服务器辅助缓存 | 高 | 高 | 中 | 中 | 强 | 6.0+ |
TTL过期策略 | 中 | 低 | 中 | 中 | 中 | 任意 |
Pub/Sub通知 | 高 | 中 | 中 | 高 | 中强 | 任意 |
根据以下因素选择合适的缓存策略:
数据一致性要求
应用架构
Redis版本
读写比例
资源限制
Redis客户端缓存是提升应用性能的强大工具,通过减少网络请求和数据库访问,可以显著降低延迟并提高吞吐量。
在实际应用中,这些策略往往不是相互排斥的,而是可以组合使用,针对不同类型的数据采用不同的缓存策略,以获得最佳性能和数据一致性平衡。
无论选择哪种缓存策略,关键是理解自己应用的数据访问模式和一致性需求,并据此设计最合适的缓存解决方案。
通过正确应用客户端缓存技术,可以在保持数据一致性的同时,显著提升系统性能和用户体验。