淺談緩存寫法(三):內存緩存該如何設計
假設有個項目有比較高的並發量,要用到多級緩存,如下:
在實際設計一個內存緩存前,需要考慮的問題:
1:內存與Redis的數據置換,盡可能在內存中提高數據命中率,減少下一級的壓力。
2:內存容量的限制,需要控制緩存數量。
3:熱點數據更新不同,需要可配置單個key過期時間。
4:良好的緩存過期刪除策略。
5:緩存數據結構的復雜度盡可能的低。
關於置換及命中率:采用LRU算法,因為它實現簡單,緩存key命中率也很好。
LRU即是:把最近最少訪問的數據給淘汰掉,經常被訪問到即是熱點數據。
關於LRU數據結構:因為key優先級提升和key淘汰,所以需要順序結構,網上大多實現都采用的這種鏈表結構。
即新數據插入到鏈表頭部、被命中時的數據移動到頭部,添加復雜度O(1),移動和獲取復雜度O(N)。
有沒復雜度更低的呢? 有Dictionary,復雜度為O(1),性能最好。 那如何保證緩存的優先級提升呢?
O(1)LRU實現
定義個LRUCache<TValue>類,構造參數maxKeySize 來控制緩存最大數量。
使用ConcurrentDictionary來作為我們的緩存容器,並能保證線程安全。
<pre style="margin:0px; padding:0px; white-space:pre-wrap; overflow-wrap:break-word; font-family:" Courier New" !important; font-size:12px !important; "> public class LRUCache<TValue>:IEnumerable<KeyValuePair<string,TValue>> { private long ageToDiscard = 0; //淘汰的年齡起點 private long currentAge = 0; //當前緩存最新年齡 private int maxSize = 0; //緩存最大容量 private readonly ConcurrentDictionary<string,TrackValue> cache; public LRUCache(int maxKeySize) { cache = new ConcurrentDictionary<string,TrackValue>(); maxSize = maxKeySize; } } </pre>
上面定義了?ageToDiscard、currentAge?這2個自增值參數,作用是標記緩存列表中各個key的新舊程度。
實現步驟如下:
每次添加key時,currentAge自增並將currentAge值分配給這個緩存值的age,currentAge一直自增。
<pre style="margin:0px; padding:0px; white-space:pre-wrap; overflow-wrap:break-word; font-family:" Courier New" !important; font-size:12px !important; "> public void Add(string key,TValue value) { Adjust(key); var result = new TrackValue(this,value); cache.AddOrUpdate(key,result,(k,o) => result); } public class TrackValue { public readonly TValue Value; public long Age; public TrackValue(LRUCache<TValue> lv,TValue tv) { Age = Interlocked.Increment(ref lv.currentAge); Value = tv; } } </pre>
在添加時,如超過最大數量,檢查字典裏是否有ageToDiscard年齡的key,如沒有循環自增檢查,有則刪除、添加成功。
其ageToDiscard+maxSize=?currentAge?,這樣設計就能在O(1)下保證可以淘汰舊數據,而不是使用鏈表移動。?
<pre style="margin:0px;
padding:0px;
white-space:pre-wrap;
overflow-wrap:break-word;
font-family:"
Courier New"
!important;
font-size:12px !important;
"> public void Adjust(string key) {
while (cache.Count >= maxSize) {
long ageToDelete = Interlocked.Increment(ref ageToDiscard);
var toDiscard = cache.FirstOrDefault(p => p.Value.Age == ageToDelete);
if (toDiscard.Key == null) continue;
TrackValue old;
cache.TryRemove(toDiscard.Key,out old);
}
}</pre>
獲取key的時候表示它又被人訪問,將最新的currentAge賦值給它,增加它的年齡:
<pre style="margin:0px;
padding:0px;
white-space:pre-wrap;
overflow-wrap:break-word;
font-family:"
Courier New"
!important;
font-size:12px !important;
"> public TValue Get(string key) {
TrackValue value=null;
if (cache.TryGetValue(key,out value)) {
value.Age = Interlocked.Increment(ref currentAge);
}
return value.Value;}
</pre>
過期刪除策略
大多數情況下,LRU算法對熱點數據命中率是很高的。 但如果突然大量偶發性的數據訪問,會讓內存中存放大量冷數據,也即是緩存汙染。
會引起LRU無法命中熱點數據,導致緩存系統命中率急劇下降,也可以使用LRU-K、2Q、MQ等變種算法來提高命中率。
過期配置
通過設定最大過期時間來盡量避免冷數據常駐內存。
多數情況每個數據緩存的時間要求不一致的,所以需要再增加單個key的過期時間字段。
<pre style="margin:0px;
padding:0px;
white-space:pre-wrap;
overflow-wrap:break-word;
font-family:"
Courier New"
!important;
font-size:12px !important;
"> private TimeSpan maxTime;
public LRUCache(int maxKeySize,TimeSpan maxExpireTime) {
}//TrackValue增加創建時間和過期時間
public readonly DateTime CreateTime;
public readonly TimeSpan ExpireTime;
</pre>
刪除策略
關於key過期刪除,最好的方式是使用定時刪除,這樣可以最快的釋放被占用的內存,但很明顯大量的定時器對CPU來說是非常不友好的。
所以需要采用惰性刪除、在獲取key的時檢查是否過期,過期直接刪除。
<pre style="margin:0px;
padding:0px;
white-space:pre-wrap;
overflow-wrap:break-word;
font-family:"
Courier New"
!important;
font-size:12px !important;
">public Tuple<TrackValue,bool> CheckExpire(string key) {
TrackValue result;
if (cache.TryGetValue(key,out result)) {
var age = DateTime.Now.Subtract(result.CreateTime);
if (age >= maxTime || age >= result.ExpireTime) {
TrackValue old;
cache.TryRemove(key,out old);
return Tuple.Create(default(TrackValue),false);
}
}return Tuple.Create(result,true);}
</pre>
惰性刪除雖然性能最好,但對於冷數據來說還是沒解決緩存汙染的問題,所以還需增加個定期清理和惰性刪除配合使用。
比如單開個線程每5分鐘去遍歷檢查key是否過期,這個時間策略是可配置的,如果緩存數量較多可分批遍歷檢查。
<pre style="margin:0px;
padding:0px;
white-space:pre-wrap;
overflow-wrap:break-word;
font-family:"
Courier New"
!important;
font-size:12px !important;
">public void Inspection() {
foreach (var item in this) {
CheckExpire(item.Key);
}
}
</pre>
惰性刪除配合定期刪除基本上能滿足絕大多數要求了。
總結
本篇參考了redis、Orleans的相關實現。
如果繼續完善下去就是內存數據庫的雛形,類似redis,比如增加刪除key的通知回調,支持更多的數據類型存儲。
淺談緩存寫法(三):內存緩存該如何設計