介绍

Caffeine是一个基于Java8开发的提供了近乎最佳命中率的高性能的缓存库。

缓存和ConcurrentMap有点相似,但还是有所区别。最根本的区别是ConcurrentMap将会持有所有加入到缓存当中的元素,直到它们被从缓存当中手动移除。

但是,Caffeine的缓存Cache 通常会被配置成自动驱逐缓存中元素,以限制其内存占用。在某些场景下,LoadingCache和AsyncLoadingCache 因为其自动加载缓存的能力将会变得非常实用。

基本使用

GitHub 官方文档:https://github.com/ben-manes/caffeine/wiki/Home-zh-CN

项目集成

使用 Caffeine 作为一级缓存,Redis 作为二级缓存。先从 Caffeine 读取缓存,如果读不到则到 Redis 中读取,如果还没有则返回 null.

模块使用了 Redis 作为二级缓存,使用 stringRedisTemplate 模板,Jedis 作为客户端。

Spring 配置

@Configuration
public class Config {
@Bean
public AbstractStringFirstCache stringFirstCache() {
// 可以随意更换底层实现,比如我们可以使用 Guava Cache,只需要 new GuavaCache() 并继承 AbstractStringFirstCache 即可
return new CaffeineCache();
} @Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
return new StringRedisTemplate(factory);
} @Bean
public JedisConnectionFactory redisConnectionFactory() {
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration("localhost", 6379);
return new JedisConnectionFactory(config);
}
}

核心代码


// 核心接口
public interface FirstCache<K, V> {
V get(@NonNull K key); void set(@NonNull K key, V value); void delete(@NonNull K key);
} public abstract class AbstractFirstCache<K, V> implements FirstCache<K, V> {
} public abstract class AbstractStringFirstCache extends AbstractFirstCache<String, String> {
abstract void set(@NonNull String key, String value, Long expertTime, TimeUnit timeUnit);
} public class CaffeineCache extends AbstractStringFirstCache { Log log = LogFactory.get(); //Hutool api @Autowired
private StringRedisTemplate stringRedisTemplate; LoadingCache<String, String> caffeineCache; public CaffeineCache() {
LoadingCache<String, String> cache = Caffeine.newBuilder()
.recordStats()
.initialCapacity(100)
.maximumSize(1000)
.writer(new CacheWriter<String, String>() {
@Override
public void write(String key, String value) {
log.info("caffeineCache write key=" + key + ", value=" + value);
} @Override
public void delete(String key, String value, RemovalCause cause) {
log.info("caffeineCache delete key=" + key);
}
})
.expireAfterWrite(30, TimeUnit.SECONDS) //一个元素将会在其创建或者最近一次被更新之后的一段时间后被认定为过期项
.build(new CacheLoader<String, String>() {
// 查询二级缓存
@Override
public @Nullable String load(@NonNull String s) throws Exception {
String value = stringRedisTemplate.opsForValue().get(s);
if (StrUtil.isEmpty(value)) {
return null;
}
return value;
}
});
caffeineCache = cache;
} @Override
public String get(String key) {
//查找缓存,如果缓存不存在则生成缓存元素
String value = caffeineCache.get(key);
log.info("get key from caffeineCache, key: " + key);
return value;
} @Override
public void set(String key, String value) {
//放入二级缓存
stringRedisTemplate.opsForValue().set(key, value);
stringRedisTemplate.expire(key, 15, TimeUnit.MINUTES);
} @Override
void set(String key, String value, Long expertTime, TimeUnit timeUnit) {
stringRedisTemplate.opsForValue().set(key, value);
stringRedisTemplate.expire(key, expertTime, timeUnit);
} @Override
public void delete(String key) {
caffeineCache.invalidate(key);
stringRedisTemplate.delete(key);
log.info("delete key from caffeineCache, key: " + key);
}
}

工具类

@Component
public class CaffeineCacheUtils { static AbstractStringFirstCache cache; @Autowired
public void setCache(AbstractStringFirstCache cache) {
CaffeineCacheUtils.cache = cache;
} /**
* 查找缓存,如果缓存不存在则生成缓存元素
*
* @return value or null
*/
public static String get(@NonNull String key) {
return cache.get(key);
} /**
* 设置缓存,默认 15min
*/
public static void set(@NonNull String key, String value) {
cache.set(key, value);
} /**
* 设置缓存,提供时间和时间单位
*/
public static void set(@NonNull String key, String value, @NonNull Long expertTime, @NonNull TimeUnit timeUnit) {
cache.set(key, value, expertTime, timeUnit);
} /**
* 删除缓存
*/
public static void delete(@NonNull String key) {
cache.delete(key);
}
}

Caffeine 缓存库的更多相关文章

  1. 高性能 Java 缓存库 — Caffeine

    http://www.baeldung.com/java-caching-caffeine 作者:baeldung 译者:oopsguy.com 1.介绍 在本文中,我们来看看 Caffeine - ...

  2. [译]高性能缓存库Caffeine介绍及实践

    概览 本文我们将介绍Caffeine-一个Java高性能缓存库.缓存和Map之间的一个根本区别是缓存会将储存的元素逐出.逐出策略决定了在什么时间应该删除哪些对象,逐出策略直接影响缓存的命中率,这是缓存 ...

  3. Caffeine缓存的简单介绍

    1.简介 在本文中,我们将了解Caffeine,一个用于Java的高性能缓存库. 缓存和Map之间的一个根本区别是缓存会清理存储的项目. 一个清理策略会决定在某个给定时间哪些对象应该被删除,这个策略直 ...

  4. Caffeine缓存

    在本文中,我们来看看 Caffeine — 一个高性能的 Java 缓存库. 缓存和 Map 之间的一个根本区别在于缓存可以回收存储的 item. 回收策略为在指定时间删除哪些对象.此策略直接影响缓存 ...

  5. picasso-强大的Android图片下载缓存库

    编辑推荐:稀土掘金,这是一个针对技术开发者的一个应用,你可以在掘金上获取最新最优质的技术干货,不仅仅是Android知识.前端.后端以至于产品和设计都有涉猎,想成为全栈工程师的朋友不要错过! pica ...

  6. 基于memcached的单机轻量级通用缓存库minicached的实现

    一.前言 之前拜读过淘宝子柳的<淘宝技术这十年>之大作,深知缓存技术在系统优化中起着一个举足轻重的作用.无论是文件系统静态文件,数据库的访问,乃至网络数据的请求,只要是与内存访问速度相差较 ...

  7. picasso_强大的Android图片下载缓存库

    tag: android pic skill date: 2016/07/09 title: picasso-强大的Android图片下载缓存库 [本文转载自:泡在网上的日子 参考:http://bl ...

  8. 毕加索的艺术——Picasso,一个强大的Android图片下载缓存库,OkHttpUtils的使用,二次封装PicassoUtils实现微信精选

    毕加索的艺术--Picasso,一个强大的Android图片下载缓存库,OkHttpUtils的使用,二次封装PicassoUtils实现微信精选 官网: http://square.github.i ...

  9. PHP缓存库phpFastCache

    phpFastCache是一个开源的PHP缓存库,只提供一个简单的PHP文件,可方便集成到已有项目,支持多种缓存方法,包括:apc, memcache, memcached, wincache, fi ...

随机推荐

  1. 1.k8s概述、安装、名词解释、资源清单

    一.k8s概述 1.简介 Kubernetes是一个开源的,用于管理云平台中多个主机上的容器化的应用,Kubernetes的目标是让部署容器化的应用简单并且高效(powerful),Kubernete ...

  2. ASP.NET Core 3.1使用Swagger

    一.什么是Swagger 随着技术的不断方法,现在的网站开发基本都是使用前后端分离的模式,这样使前端开发者和后端开发者只需要专注自己擅长的即可.但这种方式会存在一种问题:前后端通过API接口的方式进行 ...

  3. (九)rmdir和rm -r删除目录命令

    一.命令描述与格式 rmdir用于删除空目录 命令格式 :rmdir   [选项]   目录名 选项: --ignore-fail-on-non-empty   :忽略任何因目录仍有数据而造成的错误 ...

  4. Android猜数字大小游戏

    功能介绍:该程序能够提示猜大了猜小了,并且对空白输入处理,还对猜测次数限制,提供重置功能. 1.先看界面,一个输入框EditText,两个Button 2.界面设计  activity_main2.x ...

  5. 多线程写法,消除同步bug

    public class Demo01 implements Runnable { private int ticket = 10; @Override public void run() { for ...

  6. 关于客户和供应商预制凭证添加WBS字段

    客户和供应商的预制凭证的对应标准屏幕SAPLF0400301和SAPLF0400302并没有提供WBS字段,有的需求需要增强WBS字段到屏幕上,本文会介绍增强WBS字段的步骤,也请读者多多指教.为了不 ...

  7. mysql 双主复制 centos7

    mysql 安装请看:http://www.cnblogs.com/leohe/p/6839705.html 双主复制设置 1. 两台虚拟机,都是 centos7 主: 10.1.1.115 从: 1 ...

  8. Vue概述

    Vue.js是一套构建用户界面的渐进式框架,采用自底向上增量开发的设计.Vue的核心库关注于视图(html),不仅易上手,还便于与第三方库或项目整合. 渐进式:一步一步,不是将所有的东西都学完才能使用 ...

  9. 一行 CSS 代码的魅力

    之前在知乎看到一个很有意思的讨论 一行代码可以做什么? 那么,一行 CSS 代码又能不能搞点事情呢? CSS Battle 首先,这让我想到了,年初的时候沉迷的一个网站 CSS Battle .这个网 ...

  10. flume的一些使用

    一.第一层采集通道的编写 1.第一层采集脚本Source的选择①Source: 数据源在日志文件中! 读取日志中的数据,可以使用以下Source ExecSource: 可以执行一个linux命令,例 ...