浅谈缓存写法(一):缓存的雪崩和穿透

1,425 阅读7分钟

基本写法

为了方便演示,这里使用Runtime.Cache做缓存容器,并定义个简单操作类。如下:

<pre class="brush:csharp;gutter:true;" 
         style="margin: 0px; 
         padding: 0px; 
         white-space: pre-wrap; 
         overflow-wrap: break-word;"> 
public class CacheHelper
    {
        public static object Get(string cacheKey)
        {
	return HttpRuntime.Cache[cacheKey];
}
public static void Add(string cacheKey, object obj, int cacheMinute)
        {
	HttpRuntime.Cache.Insert(cacheKey, obj, null, DateTime.Now.AddMinutes(cacheMinute),
		                Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
}
}
</pre>

简单读取:

<pre class="brush:csharp;
	gutter:true;
	" style="margin:0px;
	padding:0px;
	white-space:pre-wrap;
	overflow-wrap:break-word;
	">    
public object GetMemberSigninDays1() {
	const int cacheTime = 5;
	const string cacheKey = "mushroomsir";
	var cacheValue = CacheHelper.Get(cacheKey);
	if (cacheValue != null)
	                return cacheValue;
	cacheValue = "395";
	//这里一般是 sql查询数据。 例:395 签到天数
	CacheHelper.Add(cacheKey,cacheValue,cacheTime);
	return cacheValue;
}
</pre>

在项目中,有不少这样写法,这样写并没有错,但在并发量上来后就容易出问题。

缓存雪崩

缓存雪崩是由于缓存失效(过期),新缓存未到期间。

这个中间时间内,所有请求都去查询数据库,而对数据库CPU和内存造成巨大压力,前端连接数不够、查询阻塞。

这个中间时间并没有那么短,比如sql查询1秒,加上传输解析0.5秒。  就是说1.5秒内所有用户查询,都是直接查询数据库的。

碰到这种情况,使用最多的解决方案就是加锁排队。

全局锁,实例锁

<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 static object obj1 = new object();
	public object GetMemberSigninDays2() {
	const int cacheTime = 5;
	const string cacheKey = "mushroomsir";
	var cacheValue = CacheHelper.Get(cacheKey);
	if (cacheValue != null) return cacheValue;
	//lock (obj1) //全局锁 // {
	// cacheValue = CacheHelper.Get(cacheKey);
	// if (cacheValue != null) // return cacheValue;
	// cacheValue = "395";
	//这里一般是 sql查询数据。 例:395 签到天数 // CacheHelper.Add(cacheKey,cacheValue,cacheTime);
	//
}
lock (this) {
	cacheValue = CacheHelper.Get(cacheKey);
	if (cacheValue != null) return cacheValue;
	cacheValue = "395";
	//这里一般是 sql查询数据。 例:395 签到天数
		CacheHelper.Add(cacheKey,cacheValue,cacheTime);
}
return cacheValue;}</pre>

第一种:lock (obj1)  是全局锁可以满足,但要为每个函数都声明一个obj,不然在A、B函数都锁obj1时,必然会让其中一个阻塞。

第二种:lock (this)  这个锁当前实例,对其他实例无效,那这个锁就没什么效果了,当然使用单例模式的对象可以锁。

在当前实例中:A函数锁当前实例,其他也锁当前实例的函数的读写,也被阻塞,这种做法也不可取。

字符串锁

既然锁对象不行,利用字符串的特性,直接锁缓存的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 object GetMemberSigninDays3() {
	const int cacheTime = 5;
	const string cacheKey = "mushroomsir";
	var cacheValue = CacheHelper.Get(cacheKey);
	if (cacheValue != null) return cacheValue;
	const string lockKey = cacheKey + "n(*≧▽≦*)n";
	//lock (cacheKey) // {
	// cacheValue = CacheHelper.Get(cacheKey);
	// if (cacheValue != null) // return cacheValue;
	// cacheValue = "395";
	//这里一般是 sql查询数据。 例:395 签到天数 // CacheHelper.Add(cacheKey,cacheValue,cacheTime);
	//
}
lock (lockKey) {
	cacheValue = CacheHelper.Get(cacheKey);
	if (cacheValue != null) return cacheValue;
	cacheValue = "395";
	//这里一般是 sql查询数据。 例:395 签到天数
		CacheHelper.Add(cacheKey,cacheValue,cacheTime);
}
return cacheValue;}
</pre>

第一种:lock (cacheName)  有问题,因为字符串也是共享的,会阻塞其他使用这个字符串的操作行为。

因为字符串被公共语言运行库 (CLR)暂留,这意味着整个程序中任何给定字符串都只有一个实例,所以才会用下面第二种方法。

第二种:lock (lockKey)  可以满足。其目的就是为了保证锁的粒度最小并且全局唯一性,只锁当前缓存的查询行为。

缓存穿透

先举个简单例子:一般网站经常会缓存用户搜索的结果,如果数据库查询不到,是不会做缓存的。但如果频繁查这个空关键字,会导致每次请求都直接查询数据库了

例子就是缓存穿透,请求绕过缓存直接查数据库,这也是经常提的缓存命中率问题。

<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 object GetMemberSigninDays4() {
	const int cacheTime = 5;
	const string cacheKey = "mushroomsir";
	var cacheValue = CacheHelper.Get(cacheKey);
	if (cacheValue != null) return cacheValue;
	const string lockKey = cacheKey + "n(*≧▽≦*)n";
	lock (lockKey) {
	cacheValue = CacheHelper.Get(cacheKey);
	if (cacheValue != null) return cacheValue;
	cacheValue = null;
	//数据库查询不到,为空。 //if (cacheValue2 == null) // {
	// return null;
	//一般为空,不做缓存 //
}
if (cacheValue == null) {
	cacheValue = string.Empty;
	//如果发现为空,我设置个默认值,也缓存起来。
}
CacheHelper.Add(cacheKey,cacheValue,cacheTime);}return cacheValue;}</pre>

如果把查询不到的空结果,也给缓存起来,这样下次同样的请求就可以直接返回null了,即可以避免当查询的值为空时引起的缓存穿透。

可以单独设置个缓存区域存储空值,对要查询的key进行预先校验,然后再放行给后面的正常缓存处理逻辑。

再谈缓存雪崩

前面不是用加锁排队方式就解决了吗?其实加锁排队只是为了减轻数据库的压力,本质上并没有提高系统吞吐量。

假设在高并发下,缓存重建期间key是锁着的,这是过来1000个请求999个都在阻塞的。导致的结果是用户等待超时,这是非常不优化的体验。

这种行为本质上是把多线程的Web服务器,在此时给变成单线程处理了,会导致大量的阻塞。对于系统资源也是一种浪费,因缓存重建而阻塞的线程本可以处理更多请求的。

这里提出一种解决方案是:

<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 object GetMemberSigninDays5() {
	const int cacheTime = 5;
	const string cacheKey = "mushroomsir";
	//缓存标记。
	const string cacheSign = cacheKey + "_Sign";
	var sign = CacheHelper.Get(cacheSign);
	//获取缓存值
	var cacheValue = CacheHelper.Get(cacheKey);
	if (sign != null) return cacheValue;
	//未过期,直接返回。
	lock (cacheSign) {
	sign = CacheHelper.Get(cacheSign);
	if (sign != null) return cacheValue;
	CacheHelper.Add(cacheSign,"1",cacheTime);
	ThreadPool.QueueUserWorkItem((arg) => {
	cacheValue = "395";
	//这里一般是 sql查询数据。 例:395 签到天数
		CacheHelper.Add(cacheKey,cacheValue,cacheTime*2);
	//日期设缓存时间的2倍,用于脏读。
}
);}return cacheValue;}
</pre>

从代码中看出,我们多使用了一个缓存标记key,并使用双检锁校验保证后面逻辑不会多次执行。

缓存标记key: 缓存标记key只是一个记录实际key过期时间的标记,它的缓存值可以是任意值,比如1。 它主要用来在实际key过期后,触发通知另外的线程在后台去更新实际key的缓存。

实际key:  它的过期时间会延长1倍,例:本来5分钟,现在设置为10分钟。 这样做的目的是,当缓存标记key过期后,实际缓存还能以脏数据返回给调用端,直到另外的线程在后台更新完成后,才会返回新缓存。

关于实际key的过期时间延长1倍,还是2、3倍都是可以的。只要大于正常缓存过期时间,并且能保证在延长的时间内足够拉取数据即可。

还一个好处就是,如果突然db挂了,脏数据的存在可以保证前端系统不会拿不到数据。

这样做后,就可以一定程度上提高系统吞吐量。

总结

文中说的阻塞其他函数指的是,并发情况下锁同一对象,比如一个函数锁A对象,另外的函数就必须等待A对象的锁释放后才能再次进锁。

关于更新缓存,可以单开一个线程去专门跑缓存更新,图方便的话扔线程池里面即可。

实际项目中,缓存层框架的封装往往要复杂的多,如果并发量比较小,这样写反而会增加代码的复杂度,具体要根据实际情况来取舍。