首頁  >  文章  >  後端開發  >  程式設計技術快取寫法(一)

程式設計技術快取寫法(一)

伊谢尔伦
伊谢尔伦原創
2016-11-30 09:15:561269瀏覽

介紹

本篇主要說下平常專案中快取使用經驗和遇到過的問題。

目錄

一: 基本寫法

二:緩存雪崩

1:全局鎖,實例鎖

2:字符串鎖

三:緩存穿透

四:再談緩存雪崩

五:總結

一:基本寫法

為了方便示範,我們用Runtime.Cache做快取容器,定義個簡單操作類別。如下:

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);
       }
   }

簡單讀取:

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;
    }

在專案中,有不少這樣寫法。這樣寫沒有錯,但在並發量上來後就會有問題。繼續看

二:快取雪崩

快取雪崩是由於快取失效(過期),新快取未到期間。

這個中間時間內,所有請求都去查詢資料庫,而對資料庫CPU和記憶體造成巨大壓力,前端連線數不夠、查詢阻塞。

這個中間時間並沒有那麼短,例如sql查詢1秒,加上傳輸解析0.5秒。 是說1.5秒內所有使用者查詢,都是直接查詢資料庫的。

這種情況下,我們想到最多的就是加鎖排隊了。

1:全域鎖,實例鎖

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;
       }

第一種:lock (obj1) 是全域鎖可以滿足,但我們要為每個函數都宣告一個obj,不然在A、B函數都鎖obj1時,必然會讓其中一個阻塞。

第二種:lock (this) 這個鎖目前實例,對其他實例無效,這個鎖就沒什麼效果了。使用單例模式的可以鎖。

但在目前實例中:A函數鎖定目前實例,其他鎖當前實例的函數讀寫,也被阻塞。 不可取

2:字串鎖定

既然鎖定物件不行,利用字串的特性,我們就直接鎖定快取key呢。來看下

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;
       }

第一種:lock (cacheName) 有問題,因為字串也是共享的,會阻塞其他使用這個字串的操作行為。 具體請看之前的博文 c#語言-多執行緒中的鎖系統(一)。

2015-01-04 13:36更新:因為字串被公共語言運行庫 (CLR)暫留,這意味著整個程式中任何給定字串都只有一個實例。所以才會用第二種

第二種:lock (lockKey) 可以滿足。其實是為了確保鎖的粒度最小且全域唯一性,只鎖目前快取的查詢行為。

三:快取穿透

舉個簡單例子:一般我們會快取使用者搜尋結果。而資料庫查詢不到,是不會做快取的。但如果頻繁查這個關鍵字,就會每次都直查資料庫了。

這樣快取就沒意義了,這也是常提的快取命中率問題。

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;
      }

範例中我們把查詢不到的結果,也就給快取起來了。這樣就可以避免,查詢為空時,就造成快取穿透了。

當然我們也可以單獨設定個快取區,進行第一層控制校驗。 以便和正常快取區分開了。

四:再谈缓存雪崩

额 不是用加锁排队方式就解决了吗?其实加锁排队只是为了减轻DB压力,并没有提高系统吞吐量。

在高并发下: 缓存重建期间,你是锁着的,1000个请求999个都在阻塞的。 用户体验不好,还浪费资源:阻塞的线程本可以处理后续请求的。

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;
        }

代码中,我们多用个缓存标记key,双检锁校验。它设置为正常时间,过期后通知另外的线程去更新缓存数据。

而实际的缓存由于设置了2倍的时间,仍然可以能用脏数据给前端展现。

这样就能提高不少系统吞吐量了。

五:总结

补充下: 这里说的阻塞其他函数指的是,高并发下锁同一对象。

实际使用中,缓存层封装往往要复杂的多。 关于更新缓存,可以单开一个线程去专门跑这些,图方便就扔线程池吧。

具体使用场景,可根据实际用户量来平衡。


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn