介绍

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. 安装篇八:配置 Nginx 使其支持 MySQL 应用

    配置说明 (让nginx  MySQL(中间件)之间建立关系) 第一个里程: 编写nginx.php首页文件 第二个里程:重启nginx 第三个里程:访问网页测试 打开浏览器访问:http://47. ...

  2. java实现读取excel文件内容

    package excel; import java.io.FileInputStream; import java.io.InputStream; import java.text.SimpleDa ...

  3. Idea mybatis maper接口与mapper.xml文件关联 会根据接口中的方法点在mxl中生成相应sql方法

  4. SQL语句实现增删改查

    查询语句SELECT *FROM mydriect WHERE id=1; 删除语句DELETE FROM mydriect WHERE id=1; 修改语句UPDATE mydriect SET 自 ...

  5. stm32之can总线过滤器研究

    stm32的can总线的配置如下:       CAN_InitStructure.CAN_TTCM=DISABLE;//禁止时间触发通信模式      CAN_InitStructure.CAN_A ...

  6. java零基础之--JDK安装篇

    ---恢复内容开始--- 很多零基础学习者在开始学习java中很难理解JDK的安装和配置,以下是基于Windows 7 的安装配置流程(Windows 10类似) 1. 在安装之前我们先了解几个名词: ...

  7. 对象的克隆(clone方法)

    1.深拷贝与浅拷贝 浅拷贝是指拷贝对象时仅仅拷贝对象本身(包括对象中的基本变量),而不拷贝对象包含的引用指向的对象.深拷贝不仅拷贝对象本身,而且拷贝对象包含的引用指向的所有对象. 2.深拷贝和浅拷贝的 ...

  8. dalao高精

    #ifndef MY_BIGN_H#define MY_BIGN_H 1#pragma GCC system_header#include<cstring>#include<algo ...

  9. 前端学习总结之——HTML

    近期在找工作参加面试,想总结一下学过的东西,也会持续更新遇到的新问题.盲点. 什么是HTML? 超文本标记语言(英语:HyperText Markup Language,简称:HTML),由尖括号包围 ...

  10. win7-win10 禁用IPV6临时地址

    IPV6临时地址本意是保护设备隐私,但有时候需要暂时禁用的情景下指令 netsh interface ipv6 set privacy state=disable 启用则修改最后的状态值为enable ...