Java使用Google Guava缓存

引言

使用Google Guava实现定时缓存功能

Maven仓库地址

1
2
3
4
5
6
<!--高效缓存-->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${google-guava.version}</version>
</dependency>

创建 CacheManager.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
private static CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder()
.expireAfterWrite(NumberUtils.INTEGER_TWO, TimeUnit.DAYS)
.initialCapacity(10)
.maximumSize(2000);

private static Cache<String, Object> cache;

static{
cache = cacheBuilder.build();
}

/**
* 添加缓存
* @param key key
* @param value 值
*/
public static void set(String key, Object value) {
cache.put(key,value);
}

/**
* 根据key取得缓存对象
* @param key key
* @return 结果
*/
public static Object get(String key) {
return cache.getIfPresent(key);
}

/**
* 删除缓存
* @param key key
*/
public static void del(String key){
cache.invalidate(key);
}

/**
* 判断key值是否存在
* @param key key
* @return 结果
*/
public static Boolean containsKey(String key) {
return cache.getIfPresent(key) == null ? Boolean.FALSE : Boolean.TRUE;
}

后记

持续更新… …

-------------本文结束感谢您的阅读-------------