如何在咖啡因缓存中缓存空值

我正在使用咖啡因缓存来存储从外部系统接收的数据。

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"));

结果,

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

咖啡因不在缓存中保存空值。如何在咖啡因中存储空值?

lxd2006121146 回答:如何在咖啡因缓存中缓存空值

来自this issue report

高速缓存不允许存储空值。如果执行计算并返回null,则表明数据不存在,并且调用方收到null。

此外,它还建议:

Optional是用于负缓存的好技术。

本文链接:https://www.f2er.com/2312040.html

大家都在问