具有过期和软值的基于映射的缓存
我希望在地图中缓存信息,这样我就不必保留,例如,访问数据库。在Java中,我会使用Google Collection的优秀 MapMaker 并设置一个过期时间,以保持缓存尽可能新鲜,并设置 softValues,以降低内存使用量。然后我有一个函数来计算当前未缓存的键的值。
MapMaker().softValues
.expireAfterWrite(10, TimeUnit.MINUTES)
.makeComputingMap(Function(...));
在 Scala 中执行此操作的最佳方法是什么?
I'm looking to cache information in a Map so I don't have to keep, for example, hitting a DB. In Java I'd use Google collection's excellent MapMaker and set an expiry, to keep the cache as fresh as necessary, and softValues, to keep the memory usage down. Then I'd have a function that computes the value for a key that currently isn't cached.
MapMaker().softValues
.expireAfterWrite(10, TimeUnit.MINUTES)
.makeComputingMap(Function(...));
What's the best way to do this in Scala?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如 Kim 所说,如果
MapMaker
适合您,为什么要采取不同的做法呢?现在,您可以使用 Scala 映射中的方法访问底层 Java 映射。
As Kim said, why do it differently if
MapMaker
works well for you?And now you access the underlying Java map with the methods from a Scala map.
我在 Scala 中创建了一个功能透明的过期映射。添加和删除元素会生成一个新的映射,同时也会删除所有过期的值。
过期地图
I have created a functionally transparent expiration map in Scala. Adding and removing elements gives a new map, which also removes any expired values.
Expiration Map
我也在 Scala 中继续使用 Guava 缓存解决方案:)
首先,正如其中一条评论中所述,在较新版本的 Guava Cache、
MapMaker()
现已弃用,您应该使用CacheBuilder
代替。现在,在 Scala 中,它将如下所示:
要读取它,您可以使用类似以下内容的内容:
I'm keep using Guava cache solution in Scala as well :)
First of all, as noted in one of the comments, in newer versions of Guava Cache,
MapMaker()
is now deprecated and you should useCacheBuilder
instead.So now, in Scala it will look like the follow:
To read from it, you can use something like: