javascript - 创建大型 Nodejs 缓存

标签 javascript node.js performance caching

我想为我的 REST API 创建一个大型内存缓存。如何才能在缓存变得太大时清除较旧的对象?

我在这个项目中使用nodejs。

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

这里采用的方法是在对象中存在一个指针值(_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;

最佳答案

您正在寻找所谓的“最近最少使用”(LRU) 缓存。一旦缓存的大小达到指定的阈值,它将删除最旧访问的数据。这个很受欢迎:https://www.npmjs.com/package/lru-cache

关于javascript - 创建大型 Nodejs 缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32406140/

相关文章:

javascript - 找不到模块 : Error: Can't resolve 'vue-confirm-dialog'

mysql - Node.js v10.20.1::> Sequelize findOne 速度太慢

c++ - float 组的更快 abs-max

javascript - 如果我在 throw props 中调用函数,useEffect 会显示警告吗?

node.js - Socket.io 事件多次发出

c# - 导入命名空间不使用,影响性能?

android - 1GB RAM 的 iPhone 为何与 2GB RAM 的 Android 手机具有相似的性能

javascript - 在javascript中隐藏标签

javascript - 如何在 Angular-UI-Router 中的所有命名 View 中更新作用域变量

javascript - 正则表达式替换链接