2015-09-04 47 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/ –

回答