每次在任何其他文件nodejs中引用缓存时,缓存都会重新初始化

时间:2017-09-21 12:45:28

标签: node.js caching

我正在尝试使用memory-cache npm模块在我的项目中创建内存缓存。这是

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

var get = function (key) {
    if(!_.isEmpty(secureCache)) {
        return secureCache.get(key);
    } return null;
}

var set = function (key, value, callback) {
        secureCache.put(key, value, (30*24*60*60*1000), function (key, value) {
            callback(key, value);
        })
}

module.exports = {
    get : get,
    set : set
}

现在每当我使用set通过要求这个文件来设置缓存中的键值时,它就会被设置,但是当我尝试使用get在其他文件中检索它时,它返回空。看起来变量secureCache被重新初始化。 但是,当我用

做同样的事情时
var secureCache = {};

并直接设置和访问对象的键值,我能够做到,并且对象不会重新初始化。

我的问题是这里需要做些什么。我该如何让它发挥作用?

2 个答案:

答案 0 :(得分:1)

请注意,此memory-cache仅在同一节点进程下工作,因为多个节点进程不共享相同的内存(非常感谢)。

这意味着如果您正在运行一个设置内存缓存的文件:

node set-cache.js

然后再运行另一个:

node get-cache.js

它无效。

它将在同一个流程应用程序中运行。例如,在一个文件中缓存一些数据,在另一个所需文件中检索该数据,它将起作用。例如:

// index.js
// this is your application entrypoint

const cache = require('./cache'); // this is your cache utility
const someOtherUtility = require('./utility') // this is another utility which needs access to cache

// i'm setting some cache
cache.set('testCache', 'testCacheValue', (key, value) => {
     // ... Do some stuff

     // Call a function from someOtherUtility which will return cached data
     const d = someOtherUtility.doSomething('testCache');
     console.log(d);
     // testCacheValue
}); 

your utility.js

// utility.js
const cache = require('./cache');

const doSomething = (cacheKey) => {
    return cache.get(cacheKey);  
};

此外,当使用var关键字时,当再次要求文件时,变量会重新获得。所以使用const很好。一般来说,如果您不打算覆盖您的变量,请使用const。

结论: 它与存储对象完全一样,唯一的区别是数据具有“生存时间”。

答案 1 :(得分:0)

当我们使用require关键字进行访问时,它会创建新实例。 您需要在整个应用中引用相同的实例,而不是使用require()

导入它

您可以使用global变量并在其中设置实例,并可以在同一应用程序的不同模块中引用它。

  • 例如,假设我们的应用程序入口点是app.js(即您使用node app.js命令启动应用程序)

  • 在您的应用中,导入您的secureCache并将其分配给全局变量 global.secureCache = require('secure-cache.js')

  • 您可以在任何文件中访问此全局变量,以设置或获取缓存值global.secureCache.set('mykey','myval')var myval = global.secureCache.get('mykey')

以下是有关全局变量

的更多详细信息

nodejs documentaion