如何不使用數據庫緩存,還達到實時更新
先說下當前項目的場景:
后臺人員1天不定時的,添加新聞和視頻圖片10條左右,數量不多
不使用緩存,回和數據庫打交道,非常耗時,造成效率低,尤其是在數據量非常龐大的情況下
可是加了緩存,加多少時間的緩存?新聞要保證實時更新,一發布立刻顯示出來
微軟給出了解決方法,數據庫緩存依賴項,但是貌似只能用在SQL上,而且要配置些東西;
還有,并不透明~ 一些東西看不到
這里提供另一種方法:
先說下大概思路,在所有查找操作時,都把結果插入 cache 在對數據庫有操作時(增刪改) 刪除cache
有了思路,開始解決問題,這里會遇到兩個問題
*** : 所有查找時,cache建怎么定義,保證不重復呢
第二:微軟沒有提供刪除所有cache的方法,只有cache["鍵值名"].Remove(); 而沒有removeall();
下面上代碼和解決辦法 以及思路
- #region##根據條件得到新聞
- /// <summary>
- /// 根據條件得到新聞
- /// </summary>
- /// <param name="tableName"></param>
- /// <param name="whereStr"></param>
- /// <param name="topCount"></param>
- /// <returns></returns>
- public List<CmsDemoModels.NewsInfo> GetByCondition(string whereStr, string topCount)
- {
- string cacheKey = string.Format("{0}.{1}.{2}", GetType(), "GetByCondition",whereStr+topCount);
- if (HttpRuntime.Cache[cacheKey] != null)
- {
- return HttpRuntime.Cache[cacheKey] as List<CmsDemoModels.NewsInfo>;
- }
- else
- {
- //從數據庫里查找并插入緩存
- using (CmsDemoDAL.NewsInfoServcie ns = new NewsInfoServcie())
- {
- List<NewsInfo> newsList=ns.GetByCondition(whereStr, topCount);
- HttpRuntime.Cache.Insert(cacheKey,newsList, null, DateTime.Now.AddDays(1), TimeSpan.Zero);
- return newsList;
- }
- }
- }
看上面的代碼
- string cacheKey = string.Format("{0}.{1}.{2}", GetType(), "GetByCondition",whereStr+topCount);
我定義這緩存鍵值不重復的方法是,用當前類+方法名+所有參數名的組合,來保證***性這樣把所有查詢的方法 以及查詢結果都緩存起來了~
- public static void ClearOutputCache()
- {
- //移除自定義緩存
- foreach (var item in HttpRuntime.Cache.Cast<DictionaryEntry>().ToArray())
- {
- HttpRuntime.Cache.Remove((string)item.Key);
- }
- }
上面的方法,是刪除所有緩存
可是又有個問題,我們有視頻表、圖片表、新聞等等,我現在更新個新聞,就要刪除所有的緩存,其實只用刪除所有新聞的緩存就行了
- #region 刪除緩存
- /// <summary>
- /// 根據名字開頭刪除緩存
- /// </summary>
- /// <param name="StartName">緩存名字開頭</param>
- public void RemoveAllCache(string StartName)
- {
- //移除自定義應用程序緩存
- DictionaryEntry[] de = HttpRuntime.Cache.Cast<DictionaryEntry>().ToArray();
- foreach (var item in de)
- {
- string cacheKey = item.Key.ToString();
- if (cacheKey.StartsWith(StartName))
- {
- HttpRuntime.Cache.Remove((string)item.Key);
- }
- }
- }
- #endregion
稍微改進下 效率又大大的提高了
當我們數據庫有變化時,比如添加了個新聞調用
- p.RemoveAllCache(GetType().ToString());
- #region##添加新聞
- /// <summary>
- /// 添加新聞
- /// </summary>
- /// <param name="info"></param>
- /// <returns></returns>
- public int Add(CmsDemoModels.NewsInfo info)
- {
- using (CmsDemoDAL.NewsInfoServcie ns = new NewsInfoServcie())
- {
- info.ViewCount = 0;
- info.State = 0;
- info.SortIndex = GetMaxSort() + 1;
- int i= ns.Add(info);
- PubClass p = new PubClass();
- p.RemoveAllCache(GetType().ToString());
- return i;
- }
- }
- #endregion
這樣就把所有以GetType().ToString() 開頭的刪除掉了~~ 實現新聞的刪除新聞的,視頻的刪除視頻的
PS: 這里新聞添加和查找都是在BLL層下的NewInfoManager類下,所以他們的 GetType().ToString() 會一樣大概思路就這樣
有什么問題,可以留言交流,歡迎討論~
原文鏈接:http://www.cnblogs.com/wlflovenet/archive/2011/06/30/Cache.html
【編輯推薦】