集成GuavaCache笔记

前言

Guava Cache由google开发

GuavaCache与Ehcache一样,都是使用的本地缓存,虽然在这类工具出现前可以用HashMap和ConcurrentHashMap来实现缓存操作,但终究还是Map,不具备缓存特性(缓存过期,缓存数据的加载/刷新),并且实现起来很麻烦。

使用GuavaCache一定是建立在轻量级的业务,并且存储在本地,如果业务场景复杂,并且需要分布式,集群化的大规模缓存还是使用Redis, Memcache等集中式缓存。

版本

引pom:

19是我目前使用的版本,鼓励大家关注google开源库的动向,不局限于任何版本。

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>

实际

GuavaCache不同于ehcache需要配置application.xml和ehcache.xml

特别注意:ehcache也是hibernate和spring data的二级缓存的底层,如果在配置的时候没有完全接管hibernate的ehcache配置,可能会出现多数据源同时创建ehcache对象的问题!
创建

GuavaCache直接在代码中实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static void main(String[] args) {
Cache<String, Object> cache = CacheBuilder.newBuilder()
.concurrencyLevel(8) //并发数
.expireAfterWrite(120, TimeUnit.SECONDS) //超时时间
.initialCapacity(10) //初始容量
.maximumSize(100) //最大容量,超出容量后会按照LRU活跃度算法删除缓存
.recordStats() //统计缓存命中率
.removalListener(new RemovalListener<Object, Object>() {
//超时后的回调
@Override
public void onRemoval(RemovalNotification<Object, Object> removalNotification) {
System.out.println("cache time out!");
}
})
.build();
}

上面的代码使用的是main方法来创建,如果需要Spring来管理

如果使用Spring来管理,那service会成为单例对象,注意拆分,多注入

还没做多注入

伪代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
interface cacheService
---------------------------

class GuavaCacheServiceImpl implements CacheService{
Cache<String, Object> guavaCacheService;

GuavaCacheServiceImpl(){
this.guavaCacheService = CacheBuilder.newBuilder()
.concurrencyLevel(8) //并发数
.expireAfterWrite(120, TimeUnit.SECONDS) //超时时间
...
...
...
.build();
}
}

set method:

set 无多意,map.put

1
2
3
public void set(String key, Object value) {
this.guavaCacheService.put(key, value);
}

get method:

get方法不同于redis的get,GuavaCache的get方法是两个参数的方法,第二个参数是如果key不存在的情况触发的回调

1
2
3
4
5
6
7
8
9
public Object get(String key) throws ExecutionException {
// key, key is null callback
return this.guavaCacheService.get(key, new Callable<Object>() {
@Override
public Object call() throws Exception {
return "";
}
});
}

根据上文代码优化lambda:

1
2
3
public Object get(String key) throws ExecutionException {
return this.guavaCacheService.get(key, () -> "");
}

delete method:
1
2
3
public void remove(String key) {
this.guavaCacheService.invalidate(key);
}
删除方式 API
单独删除 Cache.invalidate(key)
批量删除 Cache.invalidateAll(keys)
删除所有 Cache.invalidateAll()

参考书籍

《深入分布式缓存:从原理到实践》

未完待续,待深入