美文网首页
本地缓存caffeine

本地缓存caffeine

作者: 我还是老油条 | 来源:发表于2023-03-26 11:09 被阅读0次

项目中需要用到多级缓存实现高可用,最终方案决定是caffeine+redis

下面是实现步骤
1.引入jar包

      <!--本地缓存-->
        <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
        </dependency>    

2.增加配置类

@Configuration
public class CacheConfig {

    @Bean
    public Cache<String, Object> caffeineCache() {
        return Caffeine.newBuilder()
                // 设置最后一次写入或访问后经过固定时间过期
                .expireAfterWrite(60, TimeUnit.SECONDS)
                // 初始的缓存空间大小
                .initialCapacity(100)
                // 缓存的最大条数
                .maximumSize(10000)
                .build();
    }

}

3.查询cafefine没有的话,查询redis,后再写入caffeine

 Object value = caffeineCache.get(key, s -> redisTemplate.opsForValue().get(key));

4.最终效果

redis:
接口耗时:0.717, 返回报文:{"data":{},"message":"请求成功","status":200}

caffeine:
接口耗时:0.05, 返回报文:{"data":{},"message":"请求成功","status":200}

可以看到本地缓存性能比redis要强的多

相关文章

网友评论

      本文标题:本地缓存caffeine

      本文链接:https://www.haomeiwen.com/subject/duuordtx.html