Java 如何在缓存中缓存空值
我正在使用咖啡因缓存来存储从外部系统接收的数据Java 如何在缓存中缓存空值,java,caffeine,caffeine-cache,Java,Caffeine,Caffeine Cache,我正在使用咖啡因缓存来存储从外部系统接收的数据 LoadingCache<String, String> clientCache = Caffeine.newBuilder().expireAfterWrite(1, TimeUnit.MINUTES).build(id -> { System.out.println("Generating new value for " + id); if (id.equalsIgnoreCase("1")) { return
LoadingCache<String, String> clientCache = Caffeine.newBuilder().expireAfterWrite(1, TimeUnit.MINUTES).build(id -> {
System.out.println("Generating new value for " + id);
if (id.equalsIgnoreCase("1")) {
return null;
}
return new Date().toString();
});
System.out.println(clientCache.get("1"));
System.out.println(clientCache.get("1"));
System.out.println(clientCache.get("2"));
System.out.println(clientCache.get("3"));
咖啡因没有在缓存中保存空值。如何在咖啡因中储存空值?来源:
缓存不允许存储空值。如果执行计算并返回null,则表示数据不存在,调用方接收null
此外,它还建议:
可选
是一种很好的负缓存技术
我不知道咖啡因,但我猜它不能区分
null
意思是“我试过了,但得到了null”和“我还没试过”。也许您可以使用Optional
来代替这些值,即返回Optional.empty()
而不是返回null
。当然,那时您必须处理选项,但这可能会改进您的代码,或者至少可以通过orElse(null)
@Thomas良好的观察来适应当前的逻辑。就像Map.computeIfAbsent
一样,空返回值表示无法存储它,因此后续调用将尝试重新计算。
Generating new value for 1
null
Generating new value for 1
null
Generating new value for 2
Wed May 20 17:11:01 IST 2020
Generating new value for 3
Wed May 20 17:11:01 IST 2020
Wed May 20 17:11:01 IST 2020