IT俱乐部 Java Java本地缓存之Caffeine深入讲解

Java本地缓存之Caffeine深入讲解

1. Caffeine 简介

Caffeine 是基于 Java 8 的高性能本地缓存库,由 Google Guava 缓存改进而来。

1.1 核心特性

  • 高性能: 命中率接近最优,吞吐量远超 Guava Cache
  • 异步加载: 支持异步刷新和自动加载
  • 写入优化: 基于写入的淘汰策略
  • 过期策略: 支持基于时间、大小、引用的过期
  • 统计功能: 提供命中率、加载时间等统计信息
  • 监听器: 支持缓存事件监听

1.2 与其他缓存对比

特性 Caffeine Guava Cache Ehcache
性能 最优 较好 一般
异步支持 完整 有限 支持
API 易用性 简洁 简洁 复杂
持久化 不支持 不支持 支持
分布式 不支持 不支持 支持

1.3 性能数据

根据官方基准测试(8核心):

缓存类型           读命中率     吞吐量(ops/sec)
Caffeine             92.5%          25,764,973
Guava Cache          87.5%          19,763,654
ConcurrentHashMap    77.5%          24,282,869

2. 为什么选择 Caffeine

2.1 Window TinyLFU 算法

Caffeine 使用 W-TinyLFU 淘汰算法,结合了 LRU 和 LFU 的优点:

┌─────────────────────────────────────────────┐
│              Sketch (频率统计)               │
│   (占用内存小,统计高频访问项)                │
└─────────────────┬───────────────────────────┘
                  │
┌─────────────────▼───────────────────────────┐
│            LRU 队列 (新访问项)               │
│   (保护新热点,防止被立即淘汰)                │
└─────────────────┬───────────────────────────┘
                  │
┌─────────────────▼───────────────────────────┐
│           Probation 队列 (候选)              │
│   (待验证的热点数据)                          │
└─────────────────────────────────────────────┘

2.2 应用场景

  • 数据库查询缓存: 减少数据库压力
  • API 响应缓存: 提升接口响应速度
  • 配置信息缓存: 避免频繁读取配置
  • 计算结果缓存: 缓存复杂计算结果
  • Session 缓存: 本地会话存储

3. 快速开始

3.1 添加依赖

com.github.ben-manes.caffeinecaffeine3.1.8
// Gradle
implementation 'com.github.ben-manes.caffeine:caffeine:3.1.8'

3.2 第一个缓存示例

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;

public class CaffeineDemo {
    public static void main(String[] args) {
        // 创建缓存
        Cache cache = Caffeine.newBuilder()
            .maximumSize(10_000)
            .build();

        // 存入缓存
        cache.put("user:1001", "张三");

        // 读取缓存
        String value = cache.getIfPresent("user:1001");
        System.out.println(value); // 输出: 张三

        // 获取或计算
        String result = cache.get("user:1002", key -> {
            // 从数据库加载
            return "李四";
        });
        System.out.println(result); // 输出: 李四
    }
}

4. Caffeine 核心概念

4.1 Cache 接口

public interface Cache {
    // 读取缓存
    V getIfPresent(K key);
    V get(K key, Function mappingFunction);
    Map getAllPresent(Iterable> keys);

    // 写入缓存
    void put(K key, V value);
    void putAll(Map extends K, ? extends V> map);

    // 删除缓存
    void invalidate(K key);
    void invalidateAll(Iterable> keys);
    void invalidateAll();

    // 其他操作
    long estimatedSize();
    CacheStats stats();
    void cleanUp();
}

4.2 LoadingCache 接口

支持自动加载的缓存:

public interface LoadingCache extends Cache {
    V get(K key);
    ImmutableMap getAll(Iterable extends K> keys);
    void refresh(K key);
}

4.3 AsyncCache 接口

异步缓存:

public interface AsyncCache {
    CompletableFuture getIfPresent(K key);
    CompletableFuture get(K key, Function mappingFunction);
    CompletableFuture put(K key, V value);
}

5. 填充策略

5.1 手动填充

Cache cache = Caffeine.newBuilder()
    .maximumSize(10_000)
    .build();

// 手动 put
cache.put("user:1001", new User(1001, "张三"));

// getIfPresent - 不存在返回 null
User user = cache.getIfPresent("user:1001");

// get - 不存在则计算
User user = cache.get("user:1002", key -> {
    return userService.findById(1002);
});

5.2 自动加载

LoadingCache cache = Caffeine.newBuilder()
    .maximumSize(10_000)
    .build(key -> {
        // 自动加载逻辑
        Long userId = Long.parseLong(key.split(":")[1]);
        return userService.findById(userId);
    });

// 自动加载
User user = cache.get("user:1001");

// 批量加载
Map users = cache.getAll(
    Lists.newArrayList("user:1001", "user:1002")
);

5.3 异步加载

AsyncCache cache = Caffeine.newBuilder()
    .maximumSize(10_000)
    .buildAsync();

// 异步获取
CompletableFuture future = cache.get("user:1001", key -> {
    return userService.findById(1001);
});

// 获取结果
User user = future.join();

6. 驱逐策略

6.1 基于大小

Cache cache = Caffeine.newBuilder()
    .maximumSize(10_000)  // 最大条目数
    .build();

// 或者基于权重
Cache cache = Caffeine.newBuilder()
    .maximumWeight(100_000)  // 最大权重
    .weigher((String key, User value) -> {
        // 计算权重,例如根据对象大小
        return value.getName().length() * 2;
    })
    .build();

6.2 基于时间

Cache cache = Caffeine.newBuilder()
    // 写入后过期
    .expireAfterWrite(10, TimeUnit.MINUTES)

    // 访问后过期
    .expireAfterAccess(30, TimeUnit.MINUTES)

    // 自定义过期策略
    .expireAfter(new Expiry() {
        @Override
        public long expireAfterCreate(String key, User value, long currentTime) {
            // 创建后 10 分钟过期
            return TimeUnit.MINUTES.toNanos(10);
        }

        @Override
        public long expireAfterUpdate(String key, User value,
            long currentTime, long currentDuration) {
            // 更新后 5 分钟过期
            return TimeUnit.MINUTES.toNanos(5);
        }

        @Override
        public long expireAfterRead(String key, User value,
            long currentTime, long currentDuration) {
            // 读取后 3 分钟过期
            return TimeUnit.MINUTES.toNanos(3);
        }
    })
    .build();

6.3 基于引用

// 弱引用 key
Cache cache = Caffeine.newBuilder()
    .weakKeys()
    .build();

// 弱引用 value
Cache cache = Caffeine.newBuilder()
    .weakValues()
    .build();

// 软引用 value
Cache cache = Caffeine.newBuilder()
    .softValues()
    .build();

引用类型说明:

  • Weak Key: 当没有强引用指向 key 时,可被 GC 回收
  • Weak Value: 当没有强引用指向 value 时,可被 GC 回收
  • Soft Value: 内存不足时,GC 会回收这些对象

7. 刷新机制

7.1 刷新与驱逐的区别

  • 刷新: 重新加载 value,旧 value 在加载完成前仍可访问
  • 驱逐: 直接移除 entry,需要重新加载

7.2 自动刷新

LoadingCache cache = Caffeine.newBuilder()
    // 1 分钟后自动刷新
    .refreshAfterWrite(1, TimeUnit.MINUTES)
    .build(key -> {
        // 刷新逻辑
        return userService.findById(Long.parseLong(key.split(":")[1]));
    });

// 手动刷新
cache.refresh("user:1001");

7.3 异步刷新

AsyncLoadingCache cache = Caffeine.newBuilder()
    .refreshAfterWrite(1, TimeUnit.MINUTES)
    .buildAsync(key -> {
        // 异步刷新
        return userService.findById(Long.parseLong(key.split(":")[1]));
    });

8. 统计与监听

8.1 统计信息

Cache cache = Caffeine.newBuilder()
    .maximumSize(10_000)
    .recordStats()  // 开启统计
    .build();

// 获取统计信息
CacheStats stats = cache.stats();

System.out.println("命中次数: " + stats.hitCount());
System.out.println("未命中次数: " + stats.missCount());
System.out.println("命中率: " + stats.hitRate());
System.out.println("加载时间: " + stats.averageLoadPenalty() + "ms");
System.out.println("驱逐次数: " + stats.evictionCount());

8.2 移除监听

Cache cache = Caffeine.newBuilder()
    .maximumSize(10_000)
    .removalListener((String key, User value, RemovalCause cause) -> {
        System.out.println("key: " + key + " 被移除,原因: " + cause);
    })
    .build();

// 移除原因
// - EXPLICIT: 手动删除
// - REPLACED: 被替换
// - EXPIRED: 过期
// - SIZE: 大小超限
// - COLLECTED: GC 回收

8.3 更新监听

Cache cache = Caffeine.newBuilder()
    .maximumSize(10_000)
    .evictionListener((String key, User value, RemovalCause cause) -> {
        // 仅监听被驱逐的 entry
        System.out.println("key: " + key + " 被驱逐");
    })
    .build();

9. Spring Boot 集成

9.1 添加依赖

org.springframework.bootspring-boot-starter-cachecom.github.ben-manes.caffeinecaffeine

9.2 配置类

package com.example.cache.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.setCaffeine(Caffeine.newBuilder()
            // 初始容量
            .initialCapacity(100)
            // 最大数量
            .maximumSize(1000)
            // 写入后 5 分钟过期
            .expireAfterWrite(5, TimeUnit.MINUTES)
            // 开启统计
            .recordStats()
        );
        return cacheManager;
    }
}

9.3 多缓存配置

@Bean
public CacheManager cacheManager() {
    CaffeineCacheManager cacheManager = new CaffeineCacheManager();

    Caffeine userCache = Caffeine.newBuilder()
        .maximumSize(10_000)
        .expireAfterWrite(30, TimeUnit.MINUTES);

    Caffeine configCache = Caffeine.newBuilder()
        .maximumSize(100)
        .expireAfterWrite(1, TimeUnit.HOURS);

    cacheManager.registerCustomCache("userCache", userCache.build());
    cacheManager.registerCustomCache("configCache", configCache.build());

    return cacheManager;
}

9.4 使用注解

@Service
public class UserService {

    // 查询缓存
    @Cacheable(value = "userCache", key = "#id")
    public User findById(Long id) {
        return userMapper.findById(id);
    }

    // 更新缓存
    @CachePut(value = "userCache", key = "#user.id")
    public User update(User user) {
        userMapper.update(user);
        return user;
    }

    // 删除缓存
    @CacheEvict(value = "userCache", key = "#id")
    public void delete(Long id) {
        userMapper.delete(id);
    }

    // 删除所有缓存
    @CacheEvict(value = "userCache", allEntries = true)
    public void clear() {
    }

    // 条件缓存
    @Cacheable(value = "userCache", key = "#id",
               condition = "#id > 1000",
               unless = "#result == null")
    public User findByIdWithCondition(Long id) {
        return userMapper.findById(id);
    }
}

9.5 配置文件方式

spring:
  cache:
    type: caffeine
    caffeine:
      spec: maximumSize=10000,expireAfterWrite=5m,recordStats

    # 或者为不同 cache 指定配置
    cache-names:
      - userCache
      - configCache
    caffeine:
      specs:
        userCache: maximumSize=10000,expireAfterWrite=30m
        configCache: maximumSize=100,expireAfterWrite=1h

10. 实战案例

10.1 数据库查询缓存

@Service
public class ProductService {

    private final LoadingCache productCache;

    public ProductService(ProductRepository productRepository) {
        this.productCache = Caffeine.newBuilder()
            .maximumSize(10_000)
            .expireAfterWrite(10, TimeUnit.MINUTES)
            .recordStats()
            .build(id -> productRepository.findById(id)
                .orElseThrow(() -> new NotFoundException("商品不存在")));
    }

    public Product getProduct(Long id) {
        return productCache.get(id);
    }

    public void updateProduct(Product product) {
        productRepository.save(product);
        // 更新后刷新缓存
        productCache.refresh(product.getId());
    }

    public CacheStats getStats() {
        return productCache.stats();
    }
}

10.2 API 响应缓存

@Component
public class ApiCache {

    private final AsyncCache cache;

    public ApiCache() {
        this.cache = Caffeine.newBuilder()
            .maximumSize(5_000)
            .expireAfterWrite(2, TimeUnit.MINUTES)
            .buildAsync();
    }

    public CompletableFuture get(String url,
                                               Function loader) {
        return cache.get(url, loader);
    }

    public void invalidate(String url) {
        cache.synchronous().invalidate(url);
    }
}

10.3 多级缓存实现

@Service
public class MultiLevelCacheService {

    private final Cache localCache;
    private final RedisTemplate redisTemplate;

    public MultiLevelCacheService(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.localCache = Caffeine.newBuilder()
            .maximumSize(10_000)
            .expireAfterWrite(5, TimeUnit.MINUTES)
            .build();
    }

    public Object get(String key) {
        // L1: 本地缓存
        Object value = localCache.getIfPresent(key);
        if (value != null) {
            return value;
        }

        // L2: Redis 缓存
        value = redisTemplate.opsForValue().get(key);
        if (value != null) {
            localCache.put(key, value);
            return value;
        }

        // L3: 数据库
        value = loadFromDatabase(key);
        if (value != null) {
            redisTemplate.opsForValue().set(key, value, 30, TimeUnit.MINUTES);
            localCache.put(key, value);
        }

        return value;
    }

    public void evict(String key) {
        localCache.invalidate(key);
        redisTemplate.delete(key);
    }
}

10.4 防止缓存击穿

@Service
public class CachePenetrationService {

    private final LoadingCache userCache;

    public CachePenetrationService(UserRepository userRepository) {
        this.userCache = Caffeine.newBuilder()
            .maximumSize(10_000)
            .expireAfterWrite(10, TimeUnit.MINUTES)
            .build(id -> {
                User user = userRepository.findById(id).orElse(null);
                if (user == null) {
                    // 缓存空值,防止缓存穿透
                    return User.NULL;
                }
                return user;
            });
    }

    public User getUser(Long id) {
        User user = userCache.get(id);
        return user == User.NULL ? null : user;
    }
}

10.5 防止缓存雪崩

@Service
public class CacheAvalancheService {

    private final LoadingCache cache;

    public CacheAvalancheService() {
        this.cache = Caffeine.newBuilder()
            .maximumSize(10_000)
            // 设置随机的过期时间,防止同时过期
            .expireAfter(new Expiry() {
                @Override
                public long expireAfterCreate(String key, Object value, long currentTime) {
                    // 5-10 分钟之间的随机过期时间
                    long baseMinutes = 5;
                    long randomMinutes = ThreadLocalRandom.current().nextLong(6);
                    return TimeUnit.MINUTES.toNanos(baseMinutes + randomMinutes);
                }

                @Override
                public long expireAfterUpdate(String key, Object value,
                    long currentTime, long currentDuration) {
                    return currentDuration;
                }

                @Override
                public long expireAfterRead(String key, Object value,
                    long currentTime, long currentDuration) {
                    return currentDuration;
                }
            })
            .refreshAfterWrite(3, TimeUnit.MINUTES)
            .build(key -> loadFromDatabase(key));
    }

    private Object loadFromDatabase(String key) {
        // 数据库加载逻辑
        return null;
    }
}

11. 常见问题

11.1 Caffeine 是线程安全的吗?

是的,Caffeine 完全支持并发操作,内部使用 ConcurrentHashMap 实现。

11.2 如何选择合适的缓存大小?

根据以下因素决定:

  • 可用内存大小
  • 对象大小
  • 访问模式
// 根据内存估算
Cache cache = Caffeine.newBuilder()
    .maximumWeight(100 * 1024 * 1024)  // 100MB
    .weigher((String key, User value) -> {
        // 估算每个 entry 的大小(字节)
        return key.length() * 2 + value.estimatedSize();
    })
    .build();

11.3 缓存更新时如何保证一致性?

@Service
public class ConsistentCacheService {

    private final Cache cache;

    // 使用写锁保证一致性
    private final Striped locks = Striped.lock(128);

    public void updateWithLock(String key, Object newValue) {
        Lock lock = locks.get(key);
        lock.lock();
        try {
            // 更新数据库
            updateDatabase(key, newValue);
            // 更新缓存
            cache.put(key, newValue);
        } finally {
            lock.unlock();
        }
    }
}

11.4 如何处理缓存异常?

LoadingCache cache = Caffeine.newBuilder()
    .build(key -> {
        try {
            return userRepository.findById(Long.parseLong(key));
        } catch (Exception e) {
            // 记录异常,返回降级数据
            log.error("加载缓存失败: {}", key, e);
            return User.getDefault();  // 返回默认值
        }
    });

11.5 如何监控缓存?

@Component
public class CacheMonitor {

    private final LoadingCache cache;

    @Scheduled(fixedRate = 60000)  // 每分钟执行
    public void reportStats() {
        CacheStats stats = cache.stats();

        log.info("缓存统计 - 命中率: {:.2f}%, 命中次数: {}, 未命中次数: {}, " +
                 "加载时间: {}ms, 驱逐次数: {}",
            stats.hitRate() * 100,
            stats.hitCount(),
            stats.missCount(),
            stats.averageLoadPenalty(),
            stats.evictionCount());

        // 命中率过低时报警
        if (stats.hitRate() 

12. 最佳实践

12.1 合理设置过期时间

// 热点数据:较短过期时间
Cache hotDataCache = Caffeine.newBuilder()
    .expireAfterWrite(5, TimeUnit.MINUTES)
    .build();

// 静态数据:较长过期时间
Cache staticDataCache = Caffeine.newBuilder()
    .expireAfterWrite(1, TimeUnit.HOURS)
    .build();

12.2 使用异步加载

AsyncLoadingCache cache = Caffeine.newBuilder()
    .maximumSize(10_000)
    .buildAsync(key -> {
        // 异步加载,不阻塞调用线程
        return loadSlowly(key);
    });

12.3 监控缓存统计

Cache cache = Caffeine.newBuilder()
    .maximumSize(10_000)
    .recordStats()  // 生产环境建议开启
    .build();

12.4 处理 null 值

Object value = cache.get(key, k -> {
    Object result = loadFromDb(k);
    return result != null ? result : NullValue.INSTANCE;
});

12.5 定期清理

// 可以手动触发清理
cache.cleanUp();

// 或使用异步清理
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(() -> {
    cache.cleanUp();
}, 1, 1, TimeUnit.MINUTES);

13. 总结

Caffeine 是当前 Java 平台上性能最好的本地缓存库之一,适合以下场景:

  1. 高并发读取: Caffeine 的读性能接近 ConcurrentHashMap
  2. 需要自动加载: LoadingCache 支持自动加载
  3. 需要过期策略: 支持灵活的过期策略
  4. 需要统计监控: 内置统计功能

选择建议

  • 单机应用: 优先选择 Caffeine
  • 分布式应用: Caffeine + Redis 多级缓存
  • 大数据量: 考虑分布式缓存方案
  • 需要持久化: 考虑 Ehcache 或数据库

参考资源

  • 官方文档: https://github.com/ben-manes/caffeine
  • Spring Cache: https://docs.spring.io/spring-framework/reference/integration/cache.html
  • 性能测试: https://github.com/ben-manes/caffeine/wiki/Benchmarks

到此这篇关于Java本地缓存之Caffeine的文章就介绍到这了,更多相关Java本地缓存Caffeine内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/code/java/18784.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部