使用 Caffeine 和 Redis 实现高效的二级缓存架构

在现代应用开发中,缓存是提升系统性能的关键手段。为了兼顾本地缓存的高性能和分布式缓存的扩展能力,常见的实现方式是结合使用 Caffeine 和 Redis 实现二级缓存架构。

本文将详细介绍如何通过 Spring Boot 实现一个Caffeine + Redis 二级缓存,并通过合理的架构设计和代码实现,确保缓存的一致性、性能和容错性。

一、 需求与挑战

1.多级缓存的需求

一级缓存(Caffeine):快速响应,存储本地热点数据,减少对远程缓存和数据库的访问。二级缓存(Redis):共享缓存数据,支持分布式扩展。

2.常见问题

数据一致性:一级缓存和二级缓存之间的数据如何保持同步?容错性:Redis 不可用时如何保证系统稳定运行?缓存穿透:如何避免大量无效请求穿透缓存直接访问数据库?高并发:如何避免缓存击穿导致数据库压力激增?

二、 缓存设计与解决方案

2.1 缓存查询流程

按照Cache-Aside 模式,缓存查询流程如下:

1.查询一级缓存(Caffeine)

如果命中,则直接返回结果。

2.查询二级缓存(Redis)如果 Redis 有数据,则回填到一级缓存,并返回结果。如果 Redis 查询失败(Redis 不可用),直接跳过。3.查询数据源(数据库等)

如果 Redis 也未命中,则从数据源获取数据,同时回填到一级和二级缓存中。

2.2 缓存更新流程

数据更新或写入时,同时更新一级和二级缓存。如果 Redis 写入失败,仅更新一级缓存,确保数据可用性。

三、代码实现

3.1 缓存接口设计

定义一个通用的缓存接口,便于不同实现类的扩展和切换:

复制
import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.function.Supplier; public interface CacheService { <T> T get(String key, Class<T> type, Supplier<T> dataLoader); // 获取单个键的数据 void put(String key, Object value); // 存储单个键的数据 void evict(String key); // 删除单个键 boolean exists(String key); // 检查键是否存在 Map<String, Object> getAll(Set<String> keys); // 批量获取多个键的数据 Object getHash(String key, String hashKey); // 获取哈希表中单个字段的值 void putHash(String key, String hashKey, Object value); // 存储哈希表中的字段 void evictAll(Collection<String> keys); // 批量删除多个键 }1.2.3.4.5.6.7.8.9.10.11.12.13.14.

3.2 Caffeine + Redis 实现

使用 Caffeine 和 Redis 的结合实现二级缓存:

复制
import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; @Service public class OptimizedCacheService implements CacheService { private final Cache<String, Object> caffeineCache; private final RedisTemplate<String, Object> redisTemplate; public OptimizedCacheService(RedisTemplate<String, Object> redisTemplate) { this.caffeineCache = Caffeine.newBuilder() .initialCapacity(100) .maximumSize(1000) .expireAfterWrite(10, TimeUnit.MINUTES) .build(); this.redisTemplate = redisTemplate; } @Override public <T> T get(String key, Class<T> type, Supplier<T> dataLoader) { // Step 1: 查询一级缓存(Caffeine) T value = (T) caffeineCache.getIfPresent(key); if (value != null) { return value; } // Step 2: 查询二级缓存(Redis) try { value = (T) redisTemplate.opsForValue().get(key); if (value != null) { // 回填到一级缓存 caffeineCache.put(key, value); return value; } } catch (Exception e) { // Redis 不可用时记录日志 System.err.println("Redis 不可用:" + e.getMessage()); } // Step 3: 查询数据源(数据库等) value = dataLoader.get(); if (value != null) { // 回填到缓存 caffeineCache.put(key, value); try { redisTemplate.opsForValue().set(key, value, 10, TimeUnit.MINUTES); } catch (Exception e) { System.err.println("Redis 存储失败:" + e.getMessage()); } } return value; } @Override public void put(String key, Object value) { // 同时更新一级缓存和二级缓存 caffeineCache.put(key, value); try { redisTemplate.opsForValue().set(key, value, 10, TimeUnit.MINUTES); } catch (Exception e) { System.err.println("Redis 存储失败:" + e.getMessage()); } } @Override public void evict(String key) { // 同时移除一级缓存和二级缓存 caffeineCache.invalidate(key); try { redisTemplate.delete(key); } catch (Exception e) { System.err.println("Redis 删除失败:" + e.getMessage()); } } @Override public boolean exists(String key) { // 检查一级缓存 if (caffeineCache.asMap().containsKey(key)) { return true; } // 检查二级缓存 try { return Boolean.TRUE.equals(redisTemplate.hasKey(key)); } catch (Exception e) { System.err.println("Redis 检查键失败:" + e.getMessage()); return false; } } @Override public Map<String, Object> getAll(Set<String> keys) { // 优先从一级缓存中获取 Map<String, Object> result = caffeineCache.getAllPresent(keys); // 还需要获取的键 Set<String> missingKeys = keys.stream() .filter(key -> !result.containsKey(key)) .collect(Collectors.toSet()); if (!missingKeys.isEmpty()) { try { // 从 Redis 获取剩余的键 List<Object> redisResults = redisTemplate.opsForValue().multiGet(missingKeys); if (redisResults != null) { for (int i = 0; i < missingKeys.size(); i++) { String key = missingKeys.toArray(new String[0])[i]; Object value = redisResults.get(i); if (value != null) { result.put(key, value); caffeineCache.put(key, value); // 回填一级缓存 } } } } catch (Exception e) { System.err.println("Redis 批量获取失败:" + e.getMessage()); } } return result; } @Override public Object getHash(String key, String hashKey) { try { return redisTemplate.opsForHash().get(key, hashKey); } catch (Exception e) { System.err.println("Redis 获取哈希字段失败:" + e.getMessage()); return null; } } @Override public void putHash(String key, String hashKey, Object value) { try { redisTemplate.opsForHash().put(key, hashKey, value); } catch (Exception e) { System.err.println("Redis 存储哈希字段失败:" + e.getMessage()); } } @Override public void evictAll(Collection<String> keys) { // 删除一级缓存 caffeineCache.invalidateAll(keys); // 删除二级缓存 try { redisTemplate.delete(keys); } catch (Exception e) { System.err.println("Redis 批量删除失败:" + e.getMessage()); } } }1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.51.52.53.54.55.56.57.58.59.60.61.62.63.64.65.66.67.68.69.70.71.72.73.74.75.76.77.78.79.80.81.82.83.84.85.86.87.88.89.90.91.92.93.94.95.96.97.98.99.100.101.102.103.104.105.106.107.108.109.110.111.112.113.114.115.116.117.118.119.120.121.122.123.124.125.126.127.128.129.130.131.132.133.134.135.136.137.138.139.140.141.142.143.144.145.146.147.

3.3 空值缓存(防止缓存穿透)

为了避免查询不存在的数据穿透到数据库,可以将空值存储到缓存中:

复制
if (value == null) { // 存储空值到缓存,防止穿透 caffeineCache.put(key, "NULL"); try { redisTemplate.opsForValue().set(key, "NULL", 1, TimeUnit.MINUTES); } catch (Exception e) { System.err.println("Redis 存储空值失败:" + e.getMessage()); } return null; } if ("NULL".equals(value)) { return null; }1.2.3.4.5.6.7.8.9.10.11.12.13.

3.4 异步更新 Redis(提升写性能)

为了提高写操作性能,可以将 Redis 的更新操作放到异步线程中:

复制
private void asyncUpdateRedis(String key, Object value) { new Thread(() -> { try { redisTemplate.opsForValue().set(key, value, 10, TimeUnit.MINUTES); } catch (Exception e) { System.err.println("Redis 异步更新失败:" + e.getMessage()); } }).start(); }1.2.3.4.5.6.7.8.9.

在put和get方法中调用asyncUpdateRedis。

3.5 定时清理 Caffeine

Caffeine 默认是惰性清理(Lazy Cleanup)。如果需要主动清理,可以通过定时任务触发:

复制
@Scheduled(fixedRate = 60000) // 每分钟执行一次 public void cleanUpCache() { caffeineCache.cleanUp(); }1.2.3.4.

四、总结与优势

4.1 架构特点

性能更高:直接按一级缓存 -> 二级缓存 -> 数据库的顺序查询,减少了 Redis 可用性检查的开销。降级容错:当 Redis 不可用时,不影响数据加载和缓存更新。缓存一致性:通过回填机制,尽量保持一级缓存和二级缓存的数据一致性。可扩展性:支持空值缓存、异步更新、主动清理等增强功能。

4.2 应用场景

高频访问的数据(如热门商品、热点新闻)。分布式应用需要共享缓存的数据。对性能和容错性有较高要求的业务场景。

通过 Caffeine 和 Redis 的结合,可以构建一个高效、灵活、稳定的二级缓存架构,有效提升系统性能并降低后端服务压力。

THE END
本站服务器由亿华云赞助提供-企业级高防云服务器