本地缓存之王Caffeine
导入依赖
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>3.1.8</version>
</dependency>
基本使用
Cache<String, String> cache = Caffeine.newBuilder().build();
// 存数据
cache.put("cxk", "蔡徐坤");
// 取数据
String cxk = cache.getIfPresent("cxk");
System.out.println("cxk = " + cxk);
// 取数据库,如果没有命中,就查询数据库,然后存入缓存
String userName = cache.get("userName", key -> {
// 查询数据库
return "我是蔡徐坤";
});
System.out.println("userName = " + userName);
String userName1 = cache.getIfPresent("userName");
System.out.println("userName1 = " + userName1);
设置缓存大小
Cache<String, String> sizeCache = Caffeine.newBuilder().maximumSize(1).build();
sizeCache.put("cxk", "蔡徐坤");
sizeCache.put("cxk1", "蔡徐坤1");
//等待一段时间,让缓存失效
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String cxk1 = sizeCache.getIfPresent("cxk");
System.out.println("cxk1 = " + cxk1);
String cxk2 = sizeCache.getIfPresent("cxk1");
System.out.println("cxk2 = " + cxk2);
设置过期时间
Cache<Object, Object> cache = Caffeine.newBuilder().expireAfterWrite(Duration.ofSeconds(1)).build();
cache.put("cxk","蔡徐坤");
System.out.println(cache.getIfPresent("cxk"));
Thread.sleep(1200L);
System.out.println(cache.getIfPresent("cxk"));