Featured image of post 本地缓存 Caffeine:命中率、内存与过期策略实战

本地缓存 Caffeine:命中率、内存与过期策略实战

对比 Guava Cache 与 Caffeine,详解 W-TinyLFU 淘汰算法、maximumSize 与 maximumWeight 的区别,以及多实例场景下的缓存失效方案。

47 次

加了缓存反而更慢

给商品详情接口加了本地缓存,QPS 从 2 万涨到 11 万,P99 反而从 15ms 涨到 42ms。

jstat 显示老年代在持续增长 —— 缓存把堆撑爆了,GC 频率从每分钟 8 次涨到 60 次。

先选对工具

<!-- Guava Cache:老牌,API 简单 -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>33.0.0-jre</version>
</dependency>

<!-- Caffeine:性能更好,Spring Boot 3 默认集成 -->
<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
</dependency>

对比:

维度Guava CacheCaffeine
淘汰算法LRUW-TinyLFU
命中率(真实场景)中高 3-5%
读写性能中快 2-5 倍
异步加载❌✅
缓存统计有✅ 更详细
维护状态稳定但基本不更新活跃

命中率的差距主要来自淘汰算法。

W-TinyLFU 为什么更准

LRU 的问题

典型场景:缓存 1000 条,一次性来了 10 万条请求(每条都是不同的 key)

LRU 行为:
  请求 A 写入缓存 → 挤掉最久未用的 B
  请求 C 写入缓存 → 挤掉最久未用的 D
  ...
  结果:真正高频访问的热点数据被「一次性请求」全部冲掉

  命中率断崖式下跌

LRU 对「偶发访问」和「高频访问」一视同仁,而真实流量里热点数据和一次性请求的比例往往是 9:1。

W-TinyLFU 的做法

拆成两个区域:

┌──────────────┬────────────────┐
│   Window     │     Main       │
│   (20%)      │     (80%)      │
│  近期新增    │  主力数据      │
└──────────────┴────────────────┘

新数据先进 Window
Window 满了 → 候选者(admission)→ 比对 Main 里的数据
  频次估算(Count-Min Sketch)更高的 → 进 Main
  更低的 → 丢弃

核心优势:用「频次估算」代替「访问时间」,一次性请求进不了 Main 挤不掉热点。

实测对比

场景:缓存 1 万条,其中 100 条是热点
      流量 = 100% 命中热点的请求 + 每次都带新 key 的扫流量

Guava LRU    命中率:64%
Caffeine     命中率:91%

生产环境用 Caffeine 的命中率优势非常明显。

maximumSize 与 maximumWeight

这是最容易用错的地方。

maximumSize:按条目数

Cache<String, Product> cache = Caffeine.newBuilder()
        .maximumSize(10_000)        // 最多 1 万条
        .build();

问题:每条数据大小差异大时,内存不可控。

// 大对象场景:1 万条 × 每个 5MB = 50GB,OOM
cache.put("big-product-1", hugeProduct);
cache.put("big-product-2", hugeProduct);
...

maximumWeight:按权重

// 按对象估算大小作为权重
Cache<String, Product> cache = Caffeine.newBuilder()
        .maximumWeight(100 * 1024 * 1024)   // 总权重 100MB
        .weigher((String key, Product value) -> {
            // 估算对象占用的字节数
            return estimateSize(value);
        })
        .build();

private long estimateSize(Product product) {
    // 粗略估算:基础字段 + 字符串长度 * 2(UTF-16)
    long size = 48;   // 对象头 + 基础字段
    if (product.getTitle() != null) {
        size += product.getTitle().length() * 2;
    }
    if (product.getDescription() != null) {
        size += product.getDescription().length() * 2;
    }
    if (product.getImages() != null) {
        for (String img : product.getImages()) {
            size += img.length() * 2 + 36;   // String 对象开销
        }
    }
    return size;
}

只有 maximumWeight 能精确控制内存,这也是官方推荐的做法。

weigher 的性能注意

// ❌ 每次写入都要遍历整个集合,代价高
.weigher((key, value) -> value.getImages().size() * 1024)

// ✅ 用 O(1) 能拿到的信息
.weigher((key, value) -> value.getImageCount() * 1024)

weigher 会阻塞写入路径,必须轻量。如果是精确值需要遍历数据,考虑用「字段数 × 平均长度」这种近似算法。

过期策略

三种过期维度

Cache<String, Product> cache = Caffeine.newBuilder()
        // 写入后过期
        .expireAfterWrite(Duration.ofMinutes(30))
        // 访问后过期
        .expireAfterAccess(Duration.ofMinutes(5))
        // 自定义过期
        .expireAfter(new Expiry<String, Product>() {
            @Override
            public long expireAfterCreate(
                    String key, Product value, long currentTime) {
                return currentTime + value.getTtlSeconds() * 1000;
            }

            @Override
            public long expireAfterUpdate(
                    String key, Product value, long currentTime, long currentDuration) {
                return currentTime + value.getTtlSeconds() * 1000;
            }

            @Override
            public long expireAfterRead(
                    String key, Product value, long currentTime, long currentDuration) {
                return currentTime + value.getTtlSeconds() * 1000;
            }
        })
        .build();

TTL 加随机抖动

// ❌ 全量商品缓存同时过期 -> 缓存击穿
.expireAfterWrite(Duration.ofMinutes(30))

// ✅ 加 ±10% 抖动
.expireAfter(new Expiry<String, Product>() {
    @Override
    public long expireAfterCreate(String key, Product value, long currentTime) {
        long base = Duration.ofMinutes(30).toMillis();
        long jitter = (long) (base * 0.2 * (Math.random() - 0.5));  // ±10%
        return currentTime + base + jitter;
    }
    // 其他方法同理
});

这是防缓存击穿最简单有效的手段,一行代码解决问题。

淘汰监听器

Cache<String, Product> cache = Caffeine.newBuilder()
        .maximumWeight(100 * 1024 * 1024)
        .weigher((String key, Product value) -> estimateSize(value))
        .removalListener((String key, Product value, RemovalCause cause) -> {
            switch (cause) {
                case EXPLICIT:
                    // 主动删除(cache.invalidate(key))
                    break;
                case SIZE:
                    // 被容量限制淘汰 —— 这是最重要的回调
                    log.info("缓存被淘汰 key={} size={}MB",
                             key, value.getImageCount());
                    break;
                case EXPIRED:
                    // 过期
                    metrics.counter("cache.expired").increment();
                    break;
                case COLLECTED:
                case WROTE:
                    break;
            }
        })
        .build();

cause == SIZE 是需要重点关注的 —— 说明容量不够,缓存一直在淘汰重建。

异步加载:避免阻塞

Cache<String, Product> cache = Caffeine.newBuilder()
        .maximumSize(10_000)
        .expireAfterWrite(Duration.ofMinutes(30))
        .buildAsync(new AsyncCacheLoader<String, Product>() {
            @Override
            public CompletableFuture<Product> asyncLoad(String key, Executor executor) {
                // 在独立线程池加载,不阻塞调用方
                return CompletableFuture.supplyAsync(() -> {
                    Product p = productMapper.selectById(Long.parseLong(key));
                    if (p == null) {
                        throw new RuntimeException("商品不存在: " + key);
                    }
                    return p;
                }, executor);
            }
        });

// 使用时拿到的是 CompletableFuture
CompletableFuture<Product> future = cache.get("1001");
// 链路式处理
future.thenAccept(p -> render(p));

注意:异步加载的异常会包装成 CompletionException,且异常结果也会被缓存(直到过期)。如果希望失败不缓存:

AsyncCacheLoader<String, Product> loader = (key, executor) ->
        CompletableFuture.supplyAsync(() -> loadProduct(key), executor)
                .thenApply(product -> {
                    if (product == null) {
                        // 返回 null 不缓存;抛异常会缓存异常
                        throw new NoSuchElementException("not found: " + key);
                    }
                    return product;
                });

更严谨的做法是用 Cache<K, Optional<V>>,把「不存在」也缓存为 Optional.empty() 但设置较短 TTL。

缓存统计:上线前必须开

Cache<String, Product> cache = Caffeine.newBuilder()
        .maximumSize(10_000)
        .recordStats()                    // 开启统计
        .build();

// 定期上报
@Scheduled(fixedRate = 60_000)
public void reportStats() {
    CacheStats stats = cache.stats();

    Gauge.builder("cache.hit.rate", stats, CacheStats::hitRate)
            .tag("cache", "product").register(Metrics.globalRegistry);

    Gauge.builder("cache.size", cache, Cache::estimatedSize)
            .tag("cache", "product").register(Metrics.globalRegistry);

    Metrics.counter("cache.eviction").increment(stats.evictionCount());
    Metrics.counter("cache.miss").increment(stats.missCount());
}

recordStats() 有性能开销(约 5%),生产环境建议只在需要监控的缓存上开。

命中率判断标准:

命中率 > 95%   健康
命中率 80-95%  容量可能不足,看 evictionCount
命中率 < 80%   TTL 太短或容量太小,考虑调优或换策略

多实例下的缓存失效

这是本地缓存最大的坑:改了数据,其他实例的缓存不知道。

问题示例

实例 A: UPDATE product SET name='新名称' WHERE id=1
实例 A: 本地缓存失效  ✅
实例 B: 本地缓存还是旧数据  ❌(用户请求打到 B,看到旧名称)

方案一:短 TTL(最简单)

// TTL 设短到可接受
.expireAfterWrite(Duration.ofSeconds(30))
TTL 30s  → 最多 30 秒不一致
TTL 5m   → 最多 5 分钟不一致

适用:容忍短暂不一致的场景(商品详情、文章内容)。

方案二:广播失效(推荐)

@Component
public class CacheInvalidationPublisher {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;   // WebSocket
    @Autowired
    private StringRedisTemplate redis;

    /**
     * 发布缓存失效消息
     */
    public void publish(String cacheName, String key) {
        String message = cacheName + ":" + key;

        // 方式 1:Redis Pub/Sub(简单,但消息可能丢)
        redis.convertAndSend("cache:invalidate", message);

        // 方式 2:MQ(可靠,但延迟)
        // mqTemplate.send("cache.invalidate", message);
    }

    /**
     * 订阅失效消息
     */
    @PostConstruct
    public void subscribe() {
        redis.convertAndSend("cache:invalidate:subscribe", "ping");   // 触发订阅
    }
}

@Component
public class CacheInvalidationListener {

    @Autowired
    private ProductCache productCache;

    @MessageListener
    public void onInvalidate(String message) {
        String[] parts = message.split(":");
        if (parts.length >= 2 && "product".equals(parts[0])) {
            productCache.invalidate(parts[1]);
            log.debug("缓存失效 key={}", parts[1]);
        }
    }
}

Redis Pub/Sub 的问题:订阅者断线期间的消息会丢失。所以:

// 补偿机制:发布失效消息的同时,写入一个「失效记录」
public void publish(String cacheName, String key) {
    redis.opsForSet().add("cache:invalidated", cacheName + ":" + key);
    redis.expire("cache:invalidated", 300);      // 保留 5 分钟
    redis.convertAndSend("cache:invalidate", cacheName + ":" + key);
}

// 定时任务:定期比对失效记录与本地缓存,修正遗漏
@Scheduled(fixedRate = 60_000)
public void compensate() {
    Set<String> invalidated = redis.opsForSet().members("cache:invalidated");
    if (invalidated == null) return;

    for (String item : invalidated) {
        String[] parts = item.split(":");
        if ("product".equals(parts[0])) {
            productCache.invalidate(parts[1]);
        }
    }
    redis.delete("cache:invalidated");
}

方案三:消息队列(可靠)

// 发布
mqTemplate.send("cache-invalidate",
        CacheInvalidateMessage.of("product", "1001"));

// 消费(各实例都会收到)
@RocketMQMessageListener(topic = "cache-invalidate",
                       consumerGroup = "cache-invalidate-consumer")
public class CacheInvalidateConsumer implements RocketMQListener<CacheInvalidateMessage> {
    @Override
    public void onMessage(CacheInvalidateMessage msg) {
        productCache.invalidate(msg.getKey());
    }
}

问题:同一个 MQ 消费者组内,一条消息只会被一个实例消费。需要每个实例一个独立的消费者组:

@RocketMQMessageListener(
    topic = "cache-invalidate",
    consumerGroup = "cache-invalidate-${spring.application.name}"  // 唯一
)

方案选择

方案延迟可靠性复杂度适用
短 TTLTTL 时间内❌极低容忍旧数据
Redis Pub/Sub毫秒级⚠️ 可能丢低丢失可接受
Pub/Sub + 补偿秒级✅中多数场景推荐
MQ 独立消费者组秒级✅中一致性要求高

与 Redis 配合的两级缓存

@Service
public class ProductCache {

    private final Cache<Long, Product> localCache = Caffeine.newBuilder()
            .maximumWeight(50 * 1024 * 1024)      // 每个实例 50MB
            .weigher((Long k, Product v) -> estimateSize(v))
            .expireAfterWrite(Duration.ofMinutes(5))
            .recordStats()
            .build();

    private final StringRedisTemplate redis;

    public Product get(Long id) {
        // L1: 本地
        Product local = localCache.getIfPresent(id);
        if (local != null) return local;

        // L2: Redis
        String key = "product:" + id;
        String cached = redis.opsForValue().get(key);
        if (cached != null) {
            Product p = JsonUtils.parse(cached, Product.class);
            localCache.put(id, p);              // 回填 L1
            return p;
        }

        // L3: 数据库
        Product p = productMapper.selectById(id);
        if (p != null) {
            String json = JsonUtils.toJson(p);
            redis.opsForValue().set(key, json, 30, TimeUnit.MINUTES);
            localCache.put(id, p);
        }
        return p;
    }

    public void invalidate(Long id) {
        localCache.invalidate(id);
        redis.delete("product:" + id);
    }
}

收益:

只有本地缓存:命中率 60%,数据库压力大
只有 Redis:    命中率 90%,但每次都要网络往返(~2ms)
两级缓存:      命中率 95%,L1 命中时 < 0.1ms

常见坑

坑一:Cache 的 key 用对象

// ❌ 每次 new 出来的 key 都不相等,缓存永远不命中
cache.get(new ProductKey(id, category));

// ✅ 用不可变的 String 或记录类
cache.get(id + ":" + category);

坑二:缓存可变对象后被外部修改

Product p = cache.getIfPresent("1001");
p.setName("被改过了");    // ❌ 直接改了缓存里的对象

Caffeine 缓存的是引用。如果缓存的对象会被修改,要么返回副本,要么缓存不可变对象(用 record 或返回 DTO)。

坑三:refreshAfterWrite 的异步刷新会堆积

.refreshAfterWrite(Duration.ofSeconds(30), Duration.ofSeconds(10))

每个 key 都会触发异步加载。如果加载慢且并发高,会堆积大量加载任务。用 executor 限制并发:

.refreshAfterWrite(Duration.ofSeconds(30),
                   Duration.ofSeconds(10),
                   executor)   // 用有界线程池

坑四:没有设容量上限

// ❌ 无限增长,OOM
Cache<String, Object> cache = Caffeine.newBuilder().build();

任何本地缓存都必须设上限。这是硬性要求。

上线检查清单

【容量】
□ 设了 maximumSize 或 maximumWeight(必填)
□ 用 maximumWeight 时 weigher 是 O(1) 的

【过期】
□ 设了 TTL(expireAfterWrite / AfterAccess)
□ TTL 加了随机抖动,避免同时过期

【统计】
□ 开了 recordStats()
□ 命中率/淘汰数上报监控
□ 配置了命中率告警

【一致性】
□ 明确了可接受的不一致窗口
□ 有失效通知机制(Redis Pub/Sub 或 MQ)
□ Pub/Sub 有补偿机制

【内存】
□ 缓存总大小有上限(× 实例数 < 可用堆)
□ 压测过长时间运行后的内存曲线
□ 注意 weigher 估算是否准确

【线程池】
□ 异步加载用了独立的有界线程池
□ 线程池大小合理(不是默认的 unbounded)

内存预算怎么算

假设:4 个实例,每实例 256MB 可用堆(1GB 堆 - 业务占用 200MB - 元空间等)

预留给本地缓存:256MB × 40% = 100MB
  ↓
maximumWeight(100 * 1024 * 1024)
  ↓
反推能缓存多少条:
  单条商品数据约 2KB → 约 50000 条

注意:本地缓存在每个实例都有一份。总内存 = 单实例缓存 × 实例数。实例数增加时,每实例的缓存上限要相应调小。

一句话总结

本地缓存的价值是把网络往返的 2ms 降到 0.1ms,配合 Redis 组成两级缓存。

但它的代价是多实例一致性问题和内存占用翻倍。用之前先想清楚三件事:

  1. 内存预算是多少?
  2. 能容忍多久的数据不一致?
  3. 失效通知走哪个通道?

答不上来就别加本地缓存 —— 直接用 Redis 说不定更省事。