淺談快取寫法(三):記憶體快取該如何設計

Java_老男孩發表於2019-04-27

分析設計

假設有個專案有比較高的併發量,要用到多級快取,如下:

淺談快取寫法(三):記憶體快取該如何設計

在實際設計一個記憶體快取前,需要考慮的問題:

1:記憶體與Redis的資料置換,儘可能在記憶體中提高資料命中率,減少下一級的壓力。

2:記憶體容量的限制,需要控制快取數量。

3:熱點資料更新不同,需要可配置單個key過期時間。

4:良好的快取過期刪除策略。

5:快取資料結構的複雜度儘可能的低。

關於置換及命中率:採用LRU演算法,因為它實現簡單,快取key命中率也很好。

LRU即是:把最近最少訪問的資料給淘汰掉,經常被訪問到即是熱點資料。

關於LRU資料結構:因為key優先順序提升和key淘汰,所以需要順序結構,網上大多實現都採用的這種連結串列結構。

即新資料插入到連結串列頭部、被命中時的資料移動到頭部,新增複雜度O(1),移動和獲取複雜度O(N)。

有沒複雜度更低的呢? 有Dictionary,複雜度為O(1),效能最好。 那如何保證快取的優先順序提升呢?

O(1)LRU實現

定義個LRUCache類,構造引數maxKeySize 來控制快取最大數量。

使用ConcurrentDictionary來作為我們的快取容器,並能保證執行緒安全。

<pre style="margin:0px;
	padding:0px;
	white-space:pre-wrap;
	overflow-wrap:break-word;
	font-family:&quot;
	Courier New&quot;
	!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:&quot;
	Courier New&quot;
	!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:&quot;
	Courier New&quot;
	!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:&quot;
	Courier New&quot;
	!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:&quot;
	Courier New&quot;
	!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:&quot;
	Courier New&quot;
	!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:&quot;
	Courier New&quot;
	!important;
	font-size:12px !important;
	">public void Inspection() {
	foreach (var item in this) {
	CheckExpire(item.Key);
}
}
</pre>
複製程式碼

惰性刪除配合定期刪除基本上能滿足絕大多數要求了。

總結

本篇參考了redis、Orleans的相關實現。

如果繼續完善下去就是記憶體資料庫的雛形,類似redis,比如增加刪除key的通知回撥,支援更多的資料型別儲存。

相關文章