节点js中的LRUcaching
我需要为我的项目实施caching(对于我的组织),我们打算有一个内存LRUcaching,我有一些包,但我不知道授权条款,我发现最好的是这个
https://www.npmjs.com/package/lru-cache
但是在这里,当我声明我的caching为时,我正面临一些问题
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元素,并将所有三个元素添加到caching
还有其他的包吗?我也想实现我自己的caching机制,node js的最佳做法是什么?
让我们修改一下你的代码,这样我就可以更好地解释什么是错的。
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)
每当您在caching中设置一个值时,调用长度函数。 当你调用cache.set(1,10)
,你之前定义的函数长度作为参数:n(数字10)和key(数字1)。
所以你在这里看到key.length
是未定义的,因为一个数字没有长度属性,并且与undefined
的和将是NaN
。 在文档中,作者使用属性长度,因为通常caching键是一个string。 你当然可以使用一个数字作为关键,但这是什么突破这里。
解决这个问题后,你必须注意function的configuration。 我引用作者的话:
dispose:从caching中删除的项目上调用的函数。 如果您想要closures文件描述符,或者在项目不再可访问时执行其他清理任务,这可能非常方便。
在这个简单的情况下,我不认为你需要它,所以你可以删除它。