栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring boot集成caffeine本地缓存

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring boot集成caffeine本地缓存

呃.................................

....................废话不多说,直接干代码

1、先添加pom依赖
        
            org.springframework.boot
            spring-boot-starter-cache
        

        
            com.github.ben-manes.caffeine
            caffeine
        
spring-boot版本是:2.4.2
2、启动类添加开启缓存注解

@EnableCaching

3、添加缓存配置文件
@Configuration
public class CacheConfig {

    @Value("${cache.time}")
    private String cacheTime;


    @Bean("caffeineCacheManager")
    public CacheManager cacheManager() {
        CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
        caffeineCacheManager.setCaffeine(getCaffeine());
        caffeineCacheManager.setCacheLoader(cacheLoader());
        //是否允许值为空
        caffeineCacheManager.setAllowNullValues(false);
        return caffeineCacheManager;
    }


    @Bean
    public CacheLoader cacheLoader() {
        return new CacheLoader() {
            @Override
            public @Nullable
            Object load(@NonNull Object key) throws Exception {
                // 这里我们就可以从数据库或者其他地方查询最新的数据
                return null;
            }

            @Override
            public @Nullable
            Object reload(@NonNull Object key, @NonNull Object oldValue) throws Exception {
                System.out.println("--refresh--:" + key);
                return oldValue;
            }
        };

    }

    @Bean
    public LoadingCache getCache() {
        LoadingCache build = getCaffeine().build(cacheLoader());
        return build;
    }


    @Bean
    public Caffeine getCaffeine() {
        Integer time = Integer.parseInt(StringUtils.isEmpty(cacheTime) ? "1440" : cacheTime);
        Caffeine caffeine = Caffeine.newBuilder()
                //设置过期时间。最后一次写入或访问后过多久过期。
                .expireAfterAccess(time * 60, TimeUnit.SECONDS)
                //cache的初始容量值
                .initialCapacity(100)
                //maximumSize用来控制cache的最大缓存数量,maximumSize和maximumWeight(最大权重)不可以同时使用,
                .maximumSize(1000)
                //弱引用
                //  .weakKeys()
                //  .weakValues()
                //创建或更新之后多久刷新,需要设置cacheLoader
                //  .refreshAfterWrite(10, TimeUnit.SECONDS)
                //缓存写入/删除 监控
                .writer(new CacheWriter() {

                    @Override
                    public void write(@NonNull Object key, @NonNull Object value) {
                        System.out.println("缓存写入: key= " + key + ";value=" + value);
                    }

                    @Override
                    public void delete(@NonNull Object key, @Nullable Object value, @NonNull RemovalCause cause) {
                        System.out.println("缓存删除: key= " + key + ";value=" + value);

                    }
                })
                .recordStats();


        return caffeine;
    }
}

我这里时间是用的读取的外部配置文件,方便修改。

缓存更新策略:

expireAfterAccess(long, TimeUnit):在最后一次访问或者写入后开始计时,在指定的时间后过期。假如一直有请求访问该key,那么这个缓存将一直不会过期。
expireAfterWrite(long, TimeUnit)::在最后一次写入缓存后开始计时,在指定的时间后过期。
expireAfter(Expiry)::自定义策略,过期时间由Expiry实现独自计算。

4、使用

在需要的方法上面添加注解:@Cacheable、@CacheEvict、@CachePut

@Cacheable(cacheNames = "userInfo", key = "#param.uid+'_'+#param.uname")
    public List getUserInfo(UserParam param) {
    // 查询数据信息
}
5、完

本文内容简单,后面有时间再丰富。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/592585.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号