【问题标题】:How to synchronize cache object between multiple files in node?如何在节点中的多个文件之间同步缓存对象?
【发布时间】:2018-10-11 04:47:13
【问题描述】:

这里有三个文件。 Cacheobj 导出 File1 和 File2 使用的缓存 Obj。我想在两个文件之间同步缓存对象,即如果 file1 设置一个键值,则 file2 应该能够同步该值。

 'cacheObj.js'
  var cache = require('memory-cache');
  module.exports =new cache.Cache();



  'File1.js'
   var cache =require('./cacheObj');
   cache.put('key','val');
   console.log(cache.get('key')); //output:val


  'File2.js'
   var cache=require('./cacheObj');
   console.log(cache.get('key')); //output : null

【问题讨论】:

    标签: javascript node.js singleton memorycache


    【解决方案1】:

    将您的Cache 导出为IIFE 应该没问题:

    var Cache = (function () {
      this.storage = []; // or probably ES6 Map since it is native key:value pairs
      return this;
    })();
    
    module.exports = Cache;
    

    这是有效的,因为 node 只会调用一次缓存,即使 required 在多个文件中也是如此。

    您实际上是通过module.exports = new cache.Cache() 导出新实例,这与您想要做的相反。

    在你的情况下试试这个:

    var cache = require('memory-cache'); 
    var Cache = (function () { 
        this.storage = new cache.Cache();
        return this; 
    })(); 
    
    module.exports = Cache
    

    这是link demonstrating how this works。

    【讨论】:

    • this.storage = new cache.Cache() ??
    • 好吧,这取决于您……您使用什么基础对象来存储数据。由于您正在处理缓存,我建议您使用 ES6 Map,因为它带有开箱即用的键/值,但是如果您使用的是一些 3rd 方库,那么您肯定也可以这样做。测试一下,看看两个文件中是否有相同的数据。你会在那里提出一个不同的问题/问题。
    • 或者cacheObj中的导出可以如下:module.exports=cache;//not using new
    • var cache = require('memory-cache'); var Cache = (function () { this.storage = cache;//new cache.Cache(); return this; })(); module.exports = 缓存;`
    • 如果没有,我会感到惊讶。用确切的代码更新了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-07
    • 2021-12-06
    • 1970-01-01
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多