我正在尝试使用咖啡因缓存。如何使用 Java 为 Caffeine 缓存创建对象?我现在在我的项目中没有使用任何 Spring。
问问题
7565 次
1 回答
3
基于 Caffeine 的官方存储库和wiki,Caffeine 是一个基于 Java 8 的高性能缓存库,提供接近最佳的命中率。它的灵感来自Google Guava。
因为 Caffeine 是内存缓存,所以实例化缓存对象非常简单。
例如:
LoadingCache<Key, Graph> graphs = Caffeine.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(5, TimeUnit.MINUTES)
.refreshAfterWrite(1, TimeUnit.MINUTES)
.build(key -> createExpensiveGraph(key));
查找条目,如果未找到,则为 null:
Graph graph = graphs.getIfPresent(key);
如果不存在,则查找并计算条目,如果不可计算,则为 null:
graph = graphs.get(key, k -> createExpensiveGraph(key));
注意:
createExpensiveGraph(key)
可能是 DB getter 或实际计算图。插入或更新条目:
graphs.put(key, graph);
删除一个条目:
graphs.invalidate(key);
编辑:感谢@BenManes 的建议,我正在添加依赖项:
编辑您的pom.xml
并添加:
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>1.0.0</version>
</dependency>
于 2017-03-20T10:26:17.407 回答