[英]Guava LoadingCache - how to handle keys which don't exist in backing store
I am using CacheBuilder and LoadingCache to implement an in-memory cache of database data. 我使用CacheBuilder和LoadingCache来实现数据库数据的内存缓存。
Suppose a client queries the cache for an item that does not exist in the backing store. 假设客户端在缓存中查询后备存储中不存在的项。 I want the client to know that no data was found for the specified key.
我希望客户端知道没有找到指定密钥的数据。 What is the best approach for handling this?
处理此问题的最佳方法是什么?
I've always solved this in the following way. 我总是通过以下方式解决这个问题。
interface KeyValueService<K,V> {
V get(K key);
}
class CachingKeyValueService<K,V> {
Cache<K,Optional<V>> cache;
V get(K key) {
return cache.get(key).orNull();
}
}
Ideally you would change the interface for KeyValueService to always return Optional, but sometimes thats not possible. 理想情况下,您可以将KeyValueService的接口更改为始终返回Optional,但有时这是不可能的。
You can use weighting to cause all Optional.ABSENT references to be evicted quickly. 您可以使用权重来快速驱逐所有Optional.ABSENT引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.