多级缓存架构实战:Caffeine+Redis

发布于:2025-03-13 ⋅ 阅读:(21) ⋅ 点赞:(0)

一、架构演进与核心价值

1.1 性能对比数据
在这里插入图片描述

1.2 协同设计优势
在这里插入图片描述

二、实战案例:电商商品详情页优化

2.1 痛点分析
原始架构:单层 Redis 缓存
问题现象:

# 压测数据
Requests/sec: 58000
99% latency: 120ms
Redis CPU Usage: 85%

2.2 架构改造方案
核心依赖(Spring Boot)

<!-- Caffeine依赖 -->
<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
</dependency>

<!-- Redis依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

缓存配置

@Configuration
public class CacheConfig {
    // 本地缓存配置(Caffeine)
    @Bean
    public CacheManager caffeineCache() {
        return Caffeine.newBuilder()
            .expireAfterWrite(5, TimeUnit.SECONDS)  // 短周期防穿透
            .maximumSize(1000)
            .build();
    }

    // 分布式缓存配置(Redis)
    @Bean
    public RedisCacheManager redisCache(RedisConnectionFactory factory) {
        return RedisCacheManager.builder(factory)
            .expireAfter(30, TimeUnit.SECONDS)
            .build();
    }
}

服务层实现

@Service
public class ProductService {
    @Cacheable(value = "product", key = "#id", cacheManager = "caffeineCache")
    public Product getProduct(Long id) {
        return redisTemplate.opsForValue().get("product:" + id);
    }

    @CachePut(value = "product", key = "#result.id", cacheManager = "redisCache")
    public Product updateProduct(Product product) {
        // 更新数据库和Redis
        return product;
    }
}

三、一致性保障策略

3.1 缓存更新模式

// 双写策略
public void updateProductStock(Long productId, int delta) {
    // 1. 更新数据库
    productMapper.updateStock(productId, delta);

    // 2. 更新Redis
    redisTemplate.opsForValue().set("product:" + productId, updatedProduct);

    // 3. 逐出Caffeine缓存
    caffeineCache.evict(productId);
}

3.2 穿透/雪崩防护

// 空值防护策略
public Product getProduct(Long id) {
    Product product = caffeineCache.getIfPresent(id);
    if (product == null) {
        product = redisTemplate.opsForValue().get("product:" + id);
        if (product == null) {
            product = DB.get(id);
            if (product == null) {
                product = NULL_PRODUCT;  // 特殊空对象
            }
            redisTemplate.opsForValue().set("product:" + id, product, 60, SECONDS);
        }
        caffeineCache.put(id, product);
    }
    return product == NULL_PRODUCT ? null : product;
}

四、性能压测与调优

4.1 压测结果
在这里插入图片描述

4.2 JVM 参数优化

# 优化GC配置
-XX:+UseG1GC
-XX:MaxGCPauseMillis=100
-XX:InitiatingHeapOccupancyPercent=35

五、落地 Checklist

5.1 监控体系

# Prometheus监控指标
-pattern:"cache_hits_total"
name:"caffeine_cache_hits"
labels:
    tier:"local"
-pattern:"redis_cache_hits"
labels:
    tier:"distributed"

5.2 降级策略

// 降级开关
@HystrixCommand(fallbackMethod = "getProductFallback")
public Product getProduct(Long id) {
    // 正常逻辑
}

public Product getProductFallback(Long id) {
    return localCache.getIfPresent(id);  // 降级到本地缓存
}

5.3 冷启动策略

// 预热脚本
@PostConstruct
public void warmUpCache() {
    List<Long> hotIds = productMapper.selectHotIds(1000);
    hotIds.parallelStream().forEach(id ->
        caffeineCache.put(id, productMapper.selectById(id))
    );
}

六、总结与思考

架构设计三原则:

  • 速度优先:Caffeine 处理 80%热数据
  • 容量分层:Redis 存储全量数据
  • 最终一致:通过 MQ 实现异步同步

未来演进:

  • 结合 Service Mesh 实现无侵入缓存
  • 利用 eBPF 技术实现内核级缓存
  • 探索存算分离架构