Guava Cache是google提供的java API開發工具包的一塊。
Guava Cache是一個全內存的本地緩存實現,它提供了線程安全的實現機制。整體上來說Guava cache 是本地緩存的不二之選,簡單易用,性能好。
Guava Cache有兩種創建方式:
- 1.cacheLoader
- 2.callable callback
通過這兩種方法創建的cache,和通常用map來緩存的做法比,不同在于,這兩種方法都實現了一種邏輯——從緩存中取key X的值,如果該值已經緩存過了,則返回緩存中的值,如果沒有緩存過,可以通過某個方法來獲取這個值。但不同的在于cacheloader的定義比較寬泛,是針對整個cache定義的,可以認為是統一的根據key值load value的方法。而callable的方式較為靈活,允許你在get的時候指定。
LoadingCache方法設值
public void loadingCache() {
LoadingCache<String, String> cacheBuilder = CacheBuilder
.newBuilder()
.build(new CacheLoader<String, String>() {
@Override
public String load(String key) throws Exception {
String strProValue = "hello " + key + "!";
return strProValue;
}
});
try {
System.out.println("jerry value:" + cacheBuilder.get("jerry"));
System.out.println("peida value:" + cacheBuilder.get("peida"));
cacheBuilder.put("harry", "ssdded");
System.out.println("harry value:" + cacheBuilder.get("harry"));
} catch (ExecutionException e) {
e.printStackTrace();
}
}
如果根據key獲取value的方式一樣,可以采用這種,比較方便
Callable方式設值
public void callableCache() {
Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(1000).build();
String resultVal = null;
try {
resultVal = cache.get("jerry", new Callable<String>() {
public String call() {
String strProValue = "hello " + "jerry" + "!";
return strProValue;
}
});
System.out.println("jerry value : " + resultVal);
resultVal = cache.get("peida", new Callable<String>() {
public String call() {
String strProValue = "hello " + "peida" + "!";
return strProValue;
}
});
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("peida value : " + resultVal);
}
這個稍靈活一些,可以根據key
來靈活指定value
的生成方式。
GuavaCacheUtil工具類
public class GuavaCacheUtil {
private static volatile GuavaCacheUtil guavaCacheUtil;
public static volatile Cache cache;
public static GuavaCacheUtil getInstance() {
if (null == guavaCacheUtil) {
synchronized (GuavaCacheUtil.class) {
if (null == guavaCacheUtil) {
guavaCacheUtil = new GuavaCacheUtil();
}
}
}
return guavaCacheUtil;
}
static {
try {
//30分鐘過期
cache = CacheBuilder.newBuilder().expireAfterWrite(30, TimeUnit.MINUTES).build();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 刪除key
*
* @param key
*/
public static void remove(String key) {
cache.invalidate(key);
}
/**
* 根據key取值
*
* @param key
* @return
*/
public static Object get(String key) {
return cache.getIfPresent(key);
}
/**
* 賦值
*
* @param key
* @param value
*/
public static void put(String key, Object value) {
cache.put(key, value);
}
public static void main(String[] args) {
GuavaCacheUtil.put("name", "jack");
System.out.println(GuavaCacheUtil.get("name"));
}
}
這是簡化版的工具類,僅僅提供緩存的設置和取值功能,和EhCacheUtil的功能類似,用于cache使用場景比較多,而且需要靈活設值、刪除key的地方。
源碼下載
[本工程詳細源碼]
(https://github.com/chykong/java_component/tree/master/chapter2_2_guavaCache)