2016-02-17 69 views
-3

我使用请求来返回节点js中的值。我想将节点js中的值返回存储在内存中。此外,该值应该在应用程序启动时初始化。它如何实现?将值存储在内存节点js

回答

2

你可以简单地使用memory-cache模块,像这样在内存中存储的项目真正做到:

var cache = require('memory-cache'); 

cache.put('foo', 'bar'); 

// will print 'bar' 
console.log(cache.get('foo')) 
+0

如果MAXAGE是不确定的,是否意味着它将expried只有当服务器重新启动是? – stackdisplay

+0

据我所知,是的。 –

0

Node.js有很多缓存库。我通常在需要时使用lru-cache

var LRU = require("lru-cache") 
    , options = { max: 500 
       , length: function (n, key) { return n * 2 + key.length } 
       , dispose: function (key, n) { n.close() } 
       , maxAge: 1000 * 60 * 60 } 
    , cache = LRU(options) 
    , otherCache = LRU(50) // sets just the max size 

cache.set("key", "value") 
cache.get("key") // "value" 

// non-string keys ARE fully supported 
var someObject = {} 
cache.set(someObject, 'a value') 
cache.set('[object Object]', 'a different value') 
assert.equal(cache.get(someObject), 'a value') 

cache.reset() // empty the cache