浅谈缓存写法(三):内存缓存该如何设计

分析设计

假设有个项目有比较高的并发量,要用到多级缓存,以下:redis

在实际设计一个内存缓存前,须要考虑的问题:算法

1:内存与Redis的数据置换,尽量在内存中提升数据命中率,减小下一级的压力。数据库

2:内存容量的限制,须要控制缓存数量。缓存

3:热点数据更新不一样,须要可配置单个key过时时间。安全

4:良好的缓存过时删除策略。bash

5:缓存数据结构的复杂度尽量的低。markdown

关于置换及命中率:采用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的通知回调,支持更多的数据类型存储。

相关文章
相关标签/搜索