【问题标题】:LRU Cache in Node jsNode js中的LRU缓存
【发布时间】:2017-12-31 02:42:20
【问题描述】:

我需要为我的项目(为我的组织)实现缓存,我们计划在内存中进行 LRU 缓存,我有一些包,但我不确定许可条款,我发现的最好的是这个

https://www.npmjs.com/package/lru-cache

但是当我将缓存声明为

时,我遇到了一些问题
   var LRU = require("lru-cache")
  , options = { max: 2
              , length: function (n, key) { return n * 2 + key.length }
              , dispose: function (key, n) { n.close() }
              , maxAge: 1000 * 60 * 60 }
  , cache = LRU(options)
  console.log(cache.length)
  cache.set(1,1)
  cache.set(2,2)
  cache.set(3,3)
  console.log(cache.length)
  console.log(cache.get(1))
  console.log(cache.get(2))
  console.log(cache.get(3))
  console.log(cache)

上面代码的输出是

0
NaN
1
2
3
LRUCache {}

它没有设置最大值,它似乎是无穷大 即使长度为 2,它也不会删除 LRU 元素并将所有三个元素添加到缓存中

还有其他可用的包吗?我也在考虑实现自己的缓存机制,node js的最佳实践是什么。

【问题讨论】:

  • 你写哪一行代码来获得cache length NaN?当我复制你的代码时,我得到:cache.length === 0。你能在控制台记录对象“缓存”时显示你得到的结果吗?
  • @Wing-OnYuen 我修改了我的问题

标签: node.js caching lru


【解决方案1】:

让我们稍微修改一下您的代码,以便更好地解释问题所在。

   var LRU = require("lru-cache")
  , options = { max: 2
              , length: function (n, key) { return n * 2 + key.length }
              , dispose: function (key, n) { n.close() }
              , maxAge: 1000 * 60 * 60 }
  , cache = LRU(options)
  console.log(cache.length)
  cache.set(1,10) // differentiate the key and the value
  cache.set(2,20)
  cache.set(3,30)
  console.log(cache.length)
  console.log(cache.get(1))
  console.log(cache.get(2))
  console.log(cache.get(3))
  console.log(cache)

每次在缓存中设置值时都会调用长度函数。当您调用cache.set(1,10) 时,您之前定义的函数长度有作为参数:n(数字 10)和 key(数字 1)。

所以您在这里看到key.length 是未定义的,因为数字没有长度属性,并且与undefined 的总和将是NaN。在文档中,作者使用属性长度,因为通常缓存键是一个字符串。您当然可以使用数字作为键,但这就是这里的问题。

修复此问题后,您必须注意函数 dispose。我引用作者的话:

dispose:从缓存中删除项目时调用的函数。 如果您想关闭文件描述符或执行其他操作,这会很方便 当项目不再可访问时清理任务。

在这个简单的例子中,我认为你不需要它,所以你可以删除它。

【讨论】:

    猜你喜欢
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 2010-11-03
    • 2015-07-19
    • 1970-01-01
    相关资源
    最近更新 更多