最近發現一個好用的本地緩存,适用于資料量小,但是通路十分頻繁的場景。
Google的Guava CacheBuilder
是類似于
ConcurrentHashMap
一樣的
key-value
存儲對象,是線程安全的,
Cache
也是。有興趣的可以看一下 源碼,這裡就不多說了。
為什麼使用本地緩存,參考文章: https://www.cnblogs.com/fengli9998/p/7875027.html.
使用時先引入依賴,可在依賴圖中查找是否存在
沒有則引入依賴
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>11.0.2</version>
</dependency>
源代碼如下:
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
/**
* @author: 慌途L
*/
public class CacheUtil {
// 初始化緩存,設定5秒過期
private static final Cache<String, Object> cache = CacheBuilder.newBuilder().expireAfterWrite(5, TimeUnit.SECONDS).build();
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
while (true) {
try {
Thread.sleep(1000);
// get方法,從緩存中擷取key的值,如果為空,則請求回調方法。我這裡直接輸出随機數
// get(K key, Callable<? extends V> loader)
Object k1 = cache.get("key", () -> new Random().nextInt(10000));
System.out.println(k1);
Object k2 = cache.getIfPresent("key");
System.out.println(k2);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
});
t1.start();
}
}