Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 创建大型节点缓存_Javascript_Node.js_Performance_Caching - Fatal编程技术网

Javascript 创建大型节点缓存

Javascript 创建大型节点缓存,javascript,node.js,performance,caching,Javascript,Node.js,Performance,Caching,我想为我的RESTAPI创建一个大的内存缓存。如何使缓存过大时,旧对象被清除 我在这个项目中使用nodejs 编辑:我暂时创建了一个缓存类,这是一种可扩展且完全优化的方法吗 这里采用的方法是,对象中存在一个指针值(\u index),缓存资源将放在该值处。之后,指针将递增。一旦指针达到限制值,它将被设置回零,并且过程将继续,但此时指针上的值将被覆盖 class Cache { constructor(limit = 2048) { if (typeof limit !== 'num

我想为我的RESTAPI创建一个大的内存缓存。如何使缓存过大时,旧对象被清除

我在这个项目中使用nodejs

编辑:我暂时创建了一个缓存类,这是一种可扩展且完全优化的方法吗

这里采用的方法是,对象中存在一个指针值(
\u index
),缓存资源将放在该值处。之后,指针将递增。一旦指针达到
限制
值,它将被设置回零,并且过程将继续,但此时指针上的值将被覆盖

class Cache {
  constructor(limit = 2048) {

    if (typeof limit !== 'number' || limit <= 0) { limit = Infinity; }

    this.limit = limit;
    this.purge();
  }
  purge() {

    this._index = 0;
    this._values = [];
    this._keys = [];
  }
  put(key, value) {

    if ((let existingIndex = this._indexOf(key)) !== undefined) {
      this._keys[existingIndex] = key;
      this._values[existingIndex] = value;
    } else {
      this._keys[this._index] = key;
      this._values[this._index] = value;
      this._nextIndex();
    }
  }
  get(key) {

    let index = this._indexOf(key);
    if (index === undefined) { return; }
    return this._values[index];
  }
  delete(key) {

    let index = this._indexOf(key);
    if (index === undefined) { return false; }
    this._keys[index] = null;
    this._values[index] = null;
    return true;
  }
  has(key) {

    return this._indexOf(key) !== undefined;
  }
  _indexOf(key) {

    let i = this.limit;
    while (i--) {
      if (this._keys[i] === key) {
        return i;
      }
    }
  }
  _nextIndex() {

    this._index += 1;
    if (this._index > this.limit) { this._index = 0; }
  }
}

export default Cache;
类缓存{
建造商(限额=2048){
如果(typeof limit!='number'| | limit this.limit){this._index=0;}
}
}
导出默认缓存;

您正在寻找所谓的最近最少使用(LRU)缓存。一旦缓存的大小达到指定的阈值,它将删除最早访问的数据。这个很受欢迎:

我认为这个链接可能会有帮助: