发表于: 2017-08-19 23:11:31
1 1146
今天完成的事情:了解缓存雪崩,缓存穿透以及他们的解决方案
缓存雪崩
缓存雪崩是由于原有缓存失效(过期),新缓存未到期间。所有请求都去查询数据库,而对数据库CPU和内存造成巨大压力,严重的会造成数据库宕机。从而形成一系列连锁反应,造成整个系统崩溃。
(1) 碰到这种情况,一般并发量不是特别多的时候,使用最多的解决方案是加锁排队。
public object GetProductListNew()
{
const int cacheTime = 30;
const string cacheKey = "product_list";
const string lockKey = cacheKey;
var cacheValue = CacheHelper.Get(cacheKey);
if (cacheValue != null)
{
return cacheValue;
}
else
{
lock (lockKey)
{
cacheValue = CacheHelper.Get(cacheKey);
if (cacheValue != null)
{
return cacheValue;
}
else
{
cacheValue = GetProductListFromDB(); //这里一般是 sql查询数据。
CacheHelper.Add(cacheKey, cacheValue, cacheTime);
}
}
return cacheValue;
}
}
(2) 加锁排队只是为了减轻数据库的压力,并没有提高系统吞吐量。假设在高并发下,缓存重建期间key是锁着的,这是过来1000个请求999个都在阻塞的。同样会导致用户等待超时,这是个治标不治本的方法。
public object GetProductListNew()
{
const int cacheTime = 30;
const string cacheKey = "product_list";
//缓存标记。
const string cacheSign = cacheKey + "_sign";
var sign = CacheHelper.Get(cacheSign);
//获取缓存值
var cacheValue = CacheHelper.Get(cacheKey);
if (sign != null)
{
return cacheValue; //未过期,直接返回。
}
else
{
CacheHelper.Add(cacheSign, "1", cacheTime);
ThreadPool.QueueUserWorkItem((arg) =>
{
cacheValue = GetProductListFromDB(); //这里一般是 sql查询数据。
CacheHelper.Add(cacheKey, cacheValue, cacheTime*2); //日期设缓存时间的2倍,用于脏读。
});
return cacheValue;
}
}
还有一个解决办法解决方案是:给每一个缓存数据增加相应的缓存标记,记录缓存的是否失效,如果缓存标记失效,则更新数据缓存。
缓存标记
记录缓存数据是否过期,如果过期会触发通知另外的线程在后台去更新实际key的缓存。
缓存数据
它的过期时间比缓存标记的时间延长1倍,例:标记缓存时间30分钟,数据缓存设置为60分钟。 这样,当缓存标记key过期后,实际缓存还能把旧数据返回给调用端,直到另外的线程在后台更新完成后,才会返回新缓存。这样做后,就可以一定程度上提高系统吞吐量。
缓存穿透
缓存穿透是指用户查询数据,在数据库没有,自然在缓存中也不会有。这样就导致用户查询的时候,在缓存中找不到,每次都要去数据库再查询一遍,然后返回空。这样请求就绕过缓存直接查数据库,这也是经常提的缓存命中率问题。
解决的办法就是:如果查询数据库也为空,直接设置一个默认值存放到缓存,这样第二次到缓冲中获取就有值了,而不会继续访问数据库,这种办法最简单粗暴。
public object GetProductListNew()
{
const int cacheTime = 30;
const string cacheKey = "product_list";
var cacheValue = CacheHelper.Get(cacheKey);
if (cacheValue != null)
return cacheValue;
cacheValue = CacheHelper.Get(cacheKey);
if (cacheValue != null)
{
return cacheValue;
}
else
{
cacheValue = GetProductListFromDB(); //数据库查询不到,为空。
if (cacheValue == null)
{
cacheValue = string.Empty; //如果发现为空,设置个默认值,也缓存起来。
}
CacheHelper.Add(cacheKey, cacheValue, cacheTime);
return cacheValue;
}
}
明天计划的事情:对自己写的项目做各种测试,jmeter测试下性能
遇到的问题:没太深印象,明天疯狂测试的时候试一下
收获:
评论