gpt4 book ai didi

node.js - Node.js 中的 LRU 缓存

转载 作者:行者123 更新时间:2023-12-02 14:19:33 24 4
gpt4 key购买 nike

我需要为我的项目(为我的组织)实现缓存,我们计划有一个内存中 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 的最佳实践是什么。

最佳答案

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

   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: Function that is called on items when they are dropped from the cache. This can be handy if you want to close file descriptors or do other cleanup tasks when items are no longer accessible.

在这个简单的情况下,我认为您不需要它,因此您可以将其删除。

关于node.js - Node.js 中的 LRU 缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45298771/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com