基于多级缓存架构的Redis集群与Caffeine本地缓存实战经验分享

业务场景描述

在大规模分布式系统中,数据访问延迟和后端存储压力是常见痛点。我们在设计电商实时推荐模块时,需要满足:

  • 毫秒级读写延迟
  • 高频热点数据击穿、穿透和雪崩风险防控
  • 动态上下线、灰度发布场景下的缓存一致性
  • 系统可扩展性与高可用性要求

为此,我们引入多级缓存架构,将本地缓存(Caffeine)作为一级缓存,Redis集群作为二级缓存,并结合消息通知或异步更新策略,实现低延迟和高稳定性的缓存方案。

技术选型过程

  1. Caffeine 本地缓存:

    • 特点:高性能、支持基于权重和时间的过期策略。
    • 适用场景:热点数据的极快访问,减少跨网络调用。
  2. Redis 集群:

    • 特点:分片集群、水平扩展、支持高可用和读写分离。
    • 适用场景:全局共享缓存,支持大容量和持久化。
  3. 框架集成:

    • Spring Boot + Spring Cache 抽象层,统一注解和管理。
    • Redisson 客户端实现 Redis 集群的连接与锁机制。

通过以上选型,兼顾本地超快访问和集群高可用性,并利用 Spring Cache 简化业务调用。

实现方案详解

项目结构

复制代码
cache-example/
├── src/main/java/com/example/cache
│   ├── config
│   │   ├── CacheConfig.java        # 缓存配置类
│   │   └── RedissonConfig.java     # Redis 客户端配置
│   ├── service
│   │   └── ProductService.java     # 业务服务示例
│   └── listener
│       └── CacheMessageListener.java # 缓存失效 & 刷新消息监听
└── src/main/resources
    ├── application.yml             # 配置文件
    └── logback.xml                 # 日志配置

核心配置

application.yml

yaml 复制代码
spring:
  cache:
    type: caffeine
  redis:
    host: redis-node-1,redis-node-2,redis-node-3
    port: 6379
    timeout: 5000ms

# Caffeine 本地缓存参数
caffeine:
  spec: "maximumSize=5000,expireAfterAccess=10m"

# Redisson 客户端配置
redisson:
  cluster:
    nodeAddresses:
      - "redis://redis-node-1:6379"
      - "redis://redis-node-2:6379"
      - "redis://redis-node-3:6379"

CacheConfig.java

java 复制代码
@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public CaffeineCacheManager cacheManager() {
        CaffeineCacheManager manager = new CaffeineCacheManager();
        manager.setCaffeine(Caffeine.from("maximumSize=5000,expireAfterAccess=10m"));
        return manager;
    }

    @Bean
    public RedissonClient redissonClient(RedissonProperties props) {
        Config config = new Config();
        config.useClusterServers()
              .addNodeAddress(props.getCluster().getNodeAddresses().toArray(new String[0]));
        return Redisson.create(config);
    }
}

业务示例代码

ProductService.java

java 复制代码
@Service
public class ProductService {

    @Autowired
    private RedissonClient redissonClient;

    @Cacheable(value = "productLocalCache", key = "#id")
    public Product getProductById(Long id) {
        // 一级缓存未命中,尝试二级缓存
        String redisKey = "product:data:" + id;
        RBucket<Product> bucket = redissonClient.getBucket(redisKey);
        Product prod = bucket.get();
        if (prod != null) {
            return prod;
        }
        // 模拟数据库读取
        prod = readFromDatabase(id);
        // 更新二级缓存
        bucket.set(prod, 30, TimeUnit.MINUTES);
        return prod;
    }

    private Product readFromDatabase(Long id) {
        // 实际业务从 DAO 层查询
        return productRepository.findById(id)
                .orElseThrow(() -> new NotFoundException("Product not found"));
    }
}

缓存更新与一致性策略

  1. 采用异步消息通知机制,数据库更新后向消息队列发送失效/刷新指令。
  2. 消费者监听后,先清理一级本地缓存,再更新二级 Redis 缓存。

CacheMessageListener.java

java 复制代码
@Component
public class CacheMessageListener {

    @Autowired
    private CacheManager cacheManager;
    @Autowired
    private RedissonClient redissonClient;

    @RabbitListener(queues = "cache.update")
    public void onMessage(CacheEvent event) {
        // 清理本地缓存
        Cache cache = cacheManager.getCache("productLocalCache");
        if (cache != null) {
            cache.evict(event.getKey());
        }
        // 更新 Redis
        RBucket<Object> bucket = redissonClient.getBucket(event.getRedisKey());
        bucket.set(event.getNewValue(), 30, TimeUnit.MINUTES);
    }
}

踩过的坑与解决方案

  • 热点数据击穿:高并发请求绕过缓存直接落库。解决:实现基于 Redisson 的分布式锁,确保只有一个请求回源加载并写入缓存。

  • 本地缓存雪崩:Caffeine 重启或过期导致大规模缓存失效。解决:增加二级缓存并采用预热策略,或使用互斥加载锁降低瞬时压力。

  • 内存占用不可控 :Caffeine 未合理设置 maximumSize 导致 OOM。解决:基于业务流量分析设置合理大小,并监控内存使用。

总结与最佳实践

  1. 多级缓存结合本地 Caffeine 与远程 Redis,可兼顾低延迟与高可用性。
  2. 配置合理的过期和容量策略,避免雪崩和 OOM。
  3. 利用分布式锁、异步消息等手段,解决缓存击穿与一致性问题。
  4. 定期监控缓存命中率、内存使用与热点 Key,及时调整参数。

通过上述实践,我们在生产环境实际业务中将页面响应时间从 150ms 降至 20ms,Redis 压力降低 60%,系统整体稳定性和可扩展性显著提升。