2011-09-18 268 views
7

我需要從某些參考數據中填充一些下拉框。即城市名單,國家列表等。我需要填寫各種網絡表格。我認爲,我們應該將這些數據緩存在我們的應用程序中,這樣我們就不會在每個表單上都打上數據庫。我對緩存和ASP.Net很陌生。請告訴我如何做到這一點。ASP.Net中的數據緩存

回答

13

我總是將以下類添加到我的所有項目中,使我可以輕鬆訪問Cache對象。實現這一點,繼哈桑汗的答案將是一個很好的方法。

public static class CacheHelper 
    { 
     /// <summary> 
     /// Insert value into the cache using 
     /// appropriate name/value pairs 
     /// </summary> 
     /// <typeparam name="T">Type of cached item</typeparam> 
     /// <param name="o">Item to be cached</param> 
     /// <param name="key">Name of item</param> 
     public static void Add<T>(T o, string key, double Timeout) 
     { 
      HttpContext.Current.Cache.Insert(
       key, 
       o, 
       null, 
       DateTime.Now.AddMinutes(Timeout), 
       System.Web.Caching.Cache.NoSlidingExpiration); 
     } 

     /// <summary> 
     /// Remove item from cache 
     /// </summary> 
     /// <param name="key">Name of cached item</param> 
     public static void Clear(string key) 
     { 
      HttpContext.Current.Cache.Remove(key); 
     } 

     /// <summary> 
     /// Check for item in cache 
     /// </summary> 
     /// <param name="key">Name of cached item</param> 
     /// <returns></returns> 
     public static bool Exists(string key) 
     { 
      return HttpContext.Current.Cache[key] != null; 
     } 

     /// <summary> 
     /// Retrieve cached item 
     /// </summary> 
     /// <typeparam name="T">Type of cached item</typeparam> 
     /// <param name="key">Name of cached item</param> 
     /// <param name="value">Cached value. Default(T) if item doesn't exist.</param> 
     /// <returns>Cached item as type</returns> 
     public static bool Get<T>(string key, out T value) 
     { 
      try 
      { 
       if (!Exists(key)) 
       { 
        value = default(T); 
        return false; 
       } 

       value = (T)HttpContext.Current.Cache[key]; 
      } 
      catch 
      { 
       value = default(T); 
       return false; 
      } 

      return true; 
     } 
    } 
+0

不錯的代碼... upvoted –

2

從你的其他問題我讀到,你正在使用3層架構與達爾,業務和表示層。

所以我假設你有一些數據訪問類。理想的做法是獲得相同類的緩存實現,然後進行緩存。例如:如果你有一個IUserRepository接口,那麼UserRepository類將實現它並通過方法在db中添加/刪除/更新條目,然後你也可以擁有CachedUserRepository,它將包含UserRepository對象的實例以及它將首先看到的get方法進入緩存,對照某個鍵(從方法參數派生),如果找到該項,則返回它,否則調用內部對象上的方法;獲取數據;添加到緩存然後返回。

您的CachedUserRepository顯然也會有緩存對象的實例。有關如何使用Cache對象的詳細信息,請參閱http://msdn.microsoft.com/en-us/library/18c1wd61(v=vs.85).aspx

+1

......只是針對一般文化/詞彙,這叫做「裝飾者」模式。也就是說,你用一個額外的實現緩存的功能「裝飾」了初始倉庫。 – tsimbalar