java LRU 缓存:带时间戳的 LinkedHashMap?
java LRU cache: LinkedHashMap with a timestamp?
我需要在Java实现一个过期时间为600s的LRU缓存。我搜索并找到了内置的 LinkedHashMap class。它可以在大小超过限制时删除最旧的元素,但它没有元素的过期时间。
我能想到的就是把元素放入缓存时关联时间戳。检索元素时,检查其时间戳;如果时间戳早于 600 秒,则从缓存中删除元素并 returns 'not-found'.
有什么更好的主意吗?任何内置解决方案或最佳实践?我想避免重新发明轮子。
只使用 Guava cache 怎么样?
它支持所有these,
A builder of LoadingCache and Cache instances having any combination
of the following features:
- automatic loading of entries into the cache
- least-recently-used eviction when a maximum size is exceeded
- time-based expiration of entries, measured since last access or last write
- keys automatically wrapped in weak references
- values automatically wrapped in weak or soft references
- notification of evicted (or otherwise removed) entries
- accumulation of cache access statistics
建议不要自己实现,看看已有的实现:
- Guava Cache 是一个很好的选择(它已经被推荐所以我不会在这里添加 link)
- Caffeine 一个非常好的缓存实现。
如果您想了解两者之间的区别,请阅读
我相信两者都会让您了解功能。
此外,如果您使用 Spring 之类的框架,它会与它们集成(更高版本使用咖啡因,旧版本坚持番石榴):
我需要在Java实现一个过期时间为600s的LRU缓存。我搜索并找到了内置的 LinkedHashMap class。它可以在大小超过限制时删除最旧的元素,但它没有元素的过期时间。
我能想到的就是把元素放入缓存时关联时间戳。检索元素时,检查其时间戳;如果时间戳早于 600 秒,则从缓存中删除元素并 returns 'not-found'.
有什么更好的主意吗?任何内置解决方案或最佳实践?我想避免重新发明轮子。
只使用 Guava cache 怎么样?
它支持所有these,
A builder of LoadingCache and Cache instances having any combination of the following features:
- automatic loading of entries into the cache
- least-recently-used eviction when a maximum size is exceeded
- time-based expiration of entries, measured since last access or last write
- keys automatically wrapped in weak references
- values automatically wrapped in weak or soft references
- notification of evicted (or otherwise removed) entries
- accumulation of cache access statistics
建议不要自己实现,看看已有的实现:
- Guava Cache 是一个很好的选择(它已经被推荐所以我不会在这里添加 link)
- Caffeine 一个非常好的缓存实现。
如果您想了解两者之间的区别,请阅读
我相信两者都会让您了解功能。 此外,如果您使用 Spring 之类的框架,它会与它们集成(更高版本使用咖啡因,旧版本坚持番石榴):