2015-09-04 61 views
1

我想为我的REST API创建大型内存中缓存。我该如何做到这一点,以便当缓存变得太大时,旧的对象被清除?创建大型nodejs缓存

我正在为这个项目使用nodejs。

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

这里采用的方法是在对象中存在将放置缓存资源的指针值(_index)。之后,指针递增。一旦指针达到limit值,它将被设置回零,并且过程继续,除了指针上的这个时间值被覆盖。

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; 
+0

我觉得这个链接可能会有所帮助:http://crunchify.com/how-to-create-a-simple-in-memory-cache-in-java-lightweight-cache/ –

回答