Gauva和Caffeine的区别
- Gauva基于LRU算法,Caffeine基于W-TinyLFU算法(结合了LRU和LFU的特点)
- Caffeine支持异步加载
- Caffeine性能和开销都优于Guava
- Caffeine的命中率更高
import com.github.benmanes.caffeine.cache.*;
import org.junit.Test;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class CaffeineTest {
@Test
public void test1() {
Cache<String, String> cache = Caffeine.newBuilder()
.maximumSize(100)
.expireAfterAccess(1, TimeUnit.DAYS)
.build();
cache.put("goods", "123123asd");
System.out.println(cache.getIfPresent("goods"));
cache.invalidate("goods");
}
@Test
public void test2(){
LoadingCache<String, String> cache1 = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(10)
.build(s -> s + "_value");
System.out.println("LoadingCache自动加载:" + cache1.get("key1"));
System.out.println("---");
}
@Test
public void test3() throws ExecutionException, InterruptedException {
AsyncCache<String, String> cache2 = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(10)
.buildAsync();
CompletableFuture<String> future = cache2.get("key1", key -> key + "_value111");
System.out.println("异步手动加载:" + future.get());
System.out.println("---");
}
@Test
public void test4() throws ExecutionException, InterruptedException {
AsyncLoadingCache<String, String> cache3 = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(10)
.buildAsync(s -> s + "_syncvalue");
System.out.println("异步自动加载:" + cache3.get("key3").get());
}
}