java 高性能缓存_高性能Java缓存----Caffeine
簡單介紹
Caffeine是新出現的一個高性能的Java緩存,有了它完全可以代替Guava Cache,來實現更加高效的緩存;Caffeine采用了W-TinyLFU回收策略,集合了LRU和LFU的優點,提供了一個最佳的命中率,在效率上可以秒殺Guava Cache,下面盜取一個來自網絡的性能比較的截圖:
如何使用
Caffeine使用非常簡單,跟Guava Cache的API使用幾乎一致,下面就話不多說直接,進入代碼使用和學習中。
手動加載
import java.util.concurrent.TimeUnit;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
public class CaffeineManualLoadTest {
public static void main(String[] args) {
// 手動加載
Cache manualCache = Caffeine.newBuilder()
.expireAfterWrite(5, TimeUnit.SECONDS)
.build();
String key = "test1";
// 根據key查詢一個緩存,如果沒有則調用createTestValue方法將返回值寫到緩存
// 如果createTestValue方法返回空,則get方法返回空
// 如果createTestValue方法拋出異常,則get方法返回異常
Object oj = manualCache.get(key, k -> createTestValue(k));
System.out.println("oj = " + oj);
// 將一個值寫入緩存,如果存在就會覆蓋掉已經存在的值
manualCache.put(key, "hello world.");
oj = manualCache.getIfPresent(key);
System.out.println("oj = " + oj);
// 刪除一個緩存
manualCache.invalidate(key);
oj = manualCache.getIfPresent(key);
System.out.println("oj = " + oj);
}
private static Object createTestValue(String k) {
return null;
}
}
同步加載
import java.util.concurrent.TimeUnit;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
public class CaffeineLoadingTest {
public static void main(String[] args) {
// 同步加載
LoadingCache loadingCache = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.SECONDS)
.build(key -> createTestValue(key));
String key = "test1";
// 在獲取指定key的值的時候
// 如果沒有獲取到則通過在構建同步緩存的時候調用createTestValue方法寫入方法值
Object oj = loadingCache.get(key);
System.out.println("oj : " + oj);
}
private static Object createTestValue(String k) {
return k;
}
}
異步加載
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import com.github.benmanes.caffeine.cache.AsyncLoadingCache;
import com.github.benmanes.caffeine.cache.Caffeine;
public class CaffeineAsyncLoadTest {
public static void main(String[] args) {
// 異步加載
AsyncLoadingCache asyncLoadingCache = Caffeine.newBuilder()
.expireAfterWrite(60, TimeUnit.SECONDS)
.buildAsync(key -> createTestValue(key));
String key = "test1";
// 查詢并且在指定的key不存在的時候,通過異步的方式來構建緩存,返回的是CompletableFuture
CompletableFuture futrueOj = asyncLoadingCache.get(key);
}
private static Object createTestValue(String k) {
return "jingjing say: hello world.";
}
}
驅逐策略
1.基于大小:Caffeine.maximumSize(long),Caffeine.maximumWeight(long);注意這兩個不能同時使用。
2.基于時間:可以設置為基于秒,分等等時間策略。
3.基于引用:用到了Java中的強引用,軟引用,弱引用的概念去實現的。
總結
以上是生活随笔為你收集整理的java 高性能缓存_高性能Java缓存----Caffeine的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java数据库篇4——表的约束
- 下一篇: java美元兑换,(Java实现) 美元