本文主要是介绍Caffeine本地缓存Demo,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
- Gauva基于LRU算法,Caffeine基于W-TinyLFU算法(结合了LRU和LFU的特点) Caffeine支持异步加载 Caffeine性能和开销都优于Guava Caffeine的命中率更高
public class TestCaffeine {
public static void main(String[] args) throws Exception {
// 1、手动加载
Cache<String, String> cache = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(10)
.build();
cache.put("key1", "test1");
System.out.println("手动加载:" + cache.getIfPresent("key1"));
System.out.println("---");
// 2、LoadingCache自动加载
LoadingCache<String, String> cache1 = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(10)
.build(new CacheLoader<String, String>() {
@Override
public @Nullable
String load(@NonNull String s) throws Exception {
return s + "_value";
}
});
System.out.println("LoadingCache自动加载:" + cache1.get("key1"));
System.out.println("---");
// 3、异步手动加载
AsyncCache<String, String> cache2 = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(10)
.buildAsync();
CompletableFuture<String> future = cache2.get("key1", key -> {
return key + "_value111";
});
System.out.println("异步手动加载:" + future.get());
System.out.println("---");
// 4、异步自动加载
AsyncLoadingCache<String, String> cache3 = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(10)
.buildAsync(new CacheLoader<String, String>() {
@Override
public @Nullable
String load(@NonNull String s) throws Exception {
return s + "_syncvalue";
}
});
System.out.println("异步自动加载:" + cache3.get("key3").get());
}
这篇关于Caffeine本地缓存Demo的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!