Caffeine缓存的使用

1.springboot集成Caffeine

java 复制代码
    <!-- caffeine缓存依赖包-->
        <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
            <version>2.9.3</version>
        </dependency>

2.Cache 模式

1)普通使用

java 复制代码
  // 普通缓存
        cache = Caffeine.newBuilder()
                .expireAfterWrite(10, TimeUnit.MINUTES)
                .maximumSize(1000)  // 设置缓存的最大容量
                .build();
// 查找一个缓存元素, 没有查找到的时候返回null
MyObject graph = cache.getIfPresent(key);
// 查找缓存,如果缓存不存在则生成缓存元素,  如果无法生成则返回null
graph = cache.get(key, k -> userService.getUserCache((Integer) key));
// 添加或者更新一个缓存元素
cache.put(key, graph);
// 移除一个缓存元素
cache.invalidate(key);

2)同步缓存

java 复制代码
  // 同步自动加载缓存
        autoCache = Caffeine.newBuilder()
                .expireAfterWrite(10, TimeUnit.MINUTES)  // 设置写入后的过期时间
                .maximumSize(1000)  // 设置缓存的最大容量
                .build(key -> userService.getUserCache((Integer) key));
            //缓存未命中会自动调用当前方法,将数据库获取到的数据缓存到Caffeine

graph = cache.get(key);
// 添加或者更新一个缓存元素
cache.put(key, graph);
// 移除一个缓存元素
cache.invalidate(key);

3)异步缓存

java 复制代码
// 异步加载缓存
        asyncCache = Caffeine.newBuilder()
                .expireAfterWrite(10, TimeUnit.MINUTES)  // 设置写入后的过期时间
                .maximumSize(1000)  // 设置缓存的最大容量
                .buildAsync().synchronous();

// 查找缓存,如果缓存不存在则生成缓存元素,  如果无法生成则返回null
graph = cache.get(key, k -> userService.getUserCache((Integer) key));
// 添加或者更新一个缓存元素
cache.put(key, graph);
// 移除一个缓存元素
cache.invalidate(key);

4.异步自动缓存

java 复制代码
    // 异步自动加载缓存
        autoAsyncCache = Caffeine.newBuilder()
                .expireAfterWrite(10, TimeUnit.MINUTES)  // 设置写入后的过期时间
                .maximumSize(1000)  // 设置缓存的最大容量
                .buildAsync(key ->
                    // 异步加载缓存逻辑
                    userService.getUserCache((Integer)key)
                );
graph = cache.get(key);
// 添加或者更新一个缓存元素
cache.put(key, graph);
// 移除一个缓存元素
cache.invalidate(key);

5.自定义每个缓存过期时间

java 复制代码
  //首先自定义过期时间
        expireAfterCache = Caffeine.newBuilder().expireAfter(new Expiry<Object, Object>() {
            @Override
            public long expireAfterCreate(@NonNull Object key, @NonNull Object value, long currentTime) {
                return currentTime;
            }

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

            @Override
            public long expireAfterRead(@NonNull Object key, @NonNull Object value, long currentTime, @NonNegative long currentDuration) {
                return currentDuration;
            }
        }).maximumSize(1000).build();

// 添加或者更新一个缓存元素
 expireAfterCache.policy().expireVariably().ifPresent(p->{
//为每个key设置不同的过期时间,可自行封装下
            p.put("cs","123",5,TimeUnit.SECONDS);
        });

// 查找一个缓存元素, 没有查找到的时候返回null
MyObject graph = expireAfterCache.getIfPresent(key);

// 移除一个缓存元素
expireAfterCache.invalidate(key);
相关推荐
jack_xu27 分钟前
高频面试题:如何保证数据库和es数据一致性
后端·mysql·elasticsearch
pwzs38 分钟前
Java 中 String 转 Integer 的方法与底层原理详解
java·后端·基础
Asthenia04121 小时前
InnoDB文件存储结构与Socket技术(从Linux的FD到Java的API)
后端
普if加的帕1 小时前
java Springboot使用扣子Coze实现实时音频对话智能客服
java·开发语言·人工智能·spring boot·实时音视频·智能客服
Asthenia04121 小时前
RocketMQ 消息不丢失与持久化机制详解-生产者与Broker之间的详解
后端
〆、风神2 小时前
Spring Boot 整合 Lock4j + Redisson 实现分布式锁实战
spring boot·分布式·后端
Asthenia04122 小时前
Select、Poll、Epoll 详细分析与面试深度剖析/C代码详解
后端
烛阴2 小时前
Node.js中必备的中间件大全:提升性能、安全与开发效率的秘密武器
javascript·后端·express
南雨北斗2 小时前
WMware虚拟机下载方法(2025年4月)
后端