java 高性能缓存_高性能Java缓存----Caffeine
簡單介紹
Caffeine是新出現(xiàn)的一個(gè)高性能的Java緩存,有了它完全可以代替Guava Cache,來實(shí)現(xiàn)更加高效的緩存;Caffeine采用了W-TinyLFU回收策略,集合了LRU和LFU的優(yōu)點(diǎn),提供了一個(gè)最佳的命中率,在效率上可以秒殺Guava Cache,下面盜取一個(gè)來自網(wǎng)絡(luò)的性能比較的截圖:
如何使用
Caffeine使用非常簡單,跟Guava Cache的API使用幾乎一致,下面就話不多說直接,進(jìn)入代碼使用和學(xué)習(xí)中。
手動加載
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";
// 根據(jù)key查詢一個(gè)緩存,如果沒有則調(diào)用createTestValue方法將返回值寫到緩存
// 如果createTestValue方法返回空,則get方法返回空
// 如果createTestValue方法拋出異常,則get方法返回異常
Object oj = manualCache.get(key, k -> createTestValue(k));
System.out.println("oj = " + oj);
// 將一個(gè)值寫入緩存,如果存在就會覆蓋掉已經(jīng)存在的值
manualCache.put(key, "hello world.");
oj = manualCache.getIfPresent(key);
System.out.println("oj = " + oj);
// 刪除一個(gè)緩存
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的值的時(shí)候
// 如果沒有獲取到則通過在構(gòu)建同步緩存的時(shí)候調(diào)用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不存在的時(shí)候,通過異步的方式來構(gòu)建緩存,返回的是CompletableFuture
CompletableFuture futrueOj = asyncLoadingCache.get(key);
}
private static Object createTestValue(String k) {
return "jingjing say: hello world.";
}
}
驅(qū)逐策略
1.基于大小:Caffeine.maximumSize(long),Caffeine.maximumWeight(long);注意這兩個(gè)不能同時(shí)使用。
2.基于時(shí)間:可以設(shè)置為基于秒,分等等時(shí)間策略。
3.基于引用:用到了Java中的強(qiáng)引用,軟引用,弱引用的概念去實(shí)現(xiàn)的。
總結(jié)
以上是生活随笔為你收集整理的java 高性能缓存_高性能Java缓存----Caffeine的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java数据库篇4——表的约束
- 下一篇: 计算机更新服务,使用 Microsoft