2017-01-16 108 views
3

我正在尋找一個真正的簡單示例,說明如何將對象添加到緩存中,並將其重新取出並將其刪除。尋找一個非常簡單的緩存示例

第二個答案here是那種例子我很願意看到......

List<object> list = new List<Object>(); 

Cache["ObjectList"] = list;     // add 
list = (List<object>) Cache["ObjectList"]; // retrieve 
Cache.Remove("ObjectList");     // remove 

但是當我嘗試這一點,在第一行,我得到:

「緩存'是一種類型,在給定的上下文中無效。

而且在第三行我得到:

是必需的非靜態字段等等等等

所以一個對象的方法,讓我們說我有一個List<T> .. 。

var myList = GetListFromDB() 

現在我只想補充myList到緩存中,拿回來了,並將其刪除。

回答

9

.NET提供了一些緩存類

  • 的System.Web.Caching.Cache - 在ASP.NET默認的緩存mechanizm。你可以通過屬性Controller.HttpContext.Cache得到這個類的實例,你也可以通過單身人士HttpContext.Current.Cache得到它。這個類不希望被明確地創建,因爲它在內部使用另一個內部分配的緩存引擎。 爲了使你的代碼工作的最簡單方法是做到以下幾點:

    public class AccountController : System.Web.Mvc.Controller{ 
        public System.Web.Mvc.ActionResult Index(){ 
        List<object> list = new List<Object>(); 
    
        HttpContext.Cache["ObjectList"] = list;     // add 
        list = (List<object>)HttpContext.Cache["ObjectList"]; // retrieve 
        HttpContext.Cache.Remove("ObjectList");     // remove 
        return new System.Web.Mvc.EmptyResult(); 
        } 
    } 
    
  • System.Runtime.Caching.MemoryCache - 這個類可以在用戶的​​代碼構造。它具有不同的界面和更多的功能,如更新\刪除回調,地區,監控等。要使用它,你需要導入庫System.Runtime.Caching。它也可以用在ASP.net應用程序中,但是你將不得不自己管理它的生命週期。

    var cache = new System.Runtime.Caching.MemoryCache("MyTestCache"); 
    cache["ObjectList"] = list;     // add 
    list = (List<object>)cache["ObjectList"]; // retrieve 
    cache.Remove("ObjectList");     // remove 
    
+0

那麼,MS說:https://docs.microsoft.com/en-us/dotnet/framework/performance/caching-in-net-framework-applications,推薦使用,在新的應用程序在leats, MemoryCache命名空間。 – gatsby

1

下面是我在過去做了它的方式:

 private static string _key = "foo"; 
    private static readonly MemoryCache _cache = MemoryCache.Default; 

    //Store Stuff in the cache 
    public static void StoreItemsInCache() 
    { 
     List<string> itemsToAdd = new List<string>(); 

     //Do what you need to do here. Database Interaction, Serialization,etc. 
     var cacheItemPolicy = new CacheItemPolicy() 
     { 
     //Set your Cache expiration. 
     AbsoluteExpiration = DateTime.Now.AddDays(1) 
     }; 

     _cache.Add(_key, itemsToAdd, CacheItemPolicy); 
    } 

    //Get stuff from the cache 
    public static List<string> GetItemsFromCache() 
    { 
     if (!_cache.Contains(_key)) 
       StoreItemsInCache(); 

     return _cache.Get(_key) as List<string>; 
    } 

編輯:格式化。

順便說一句,你可以做任何事情。我用這個與序列化結合來存儲和檢索一個150K項目的List對象。

2

如果您使用的MemoryCache這裏是一個很簡單的例子:

var cache = MemoryCache.Default; 

var key = "myKey"; 
var value = "my value"; 
var policy = new CacheItemPolicy { SlidingExpiration = new TimeSpan(2, 0, 0) }; 
cache.Add(key, value, policy); 

Console.Write(cache[key]); 
0

試試這個第三方緩存:CacheCrow,這是一個簡單的基於LFU緩存。

使用Visual Studio中的PowerShell命令安裝:Install-Package CacheCrow

代碼段:

// initialization of singleton class 
    ICacheCrow<string, string> cache = CacheCrow<string, string>.Initialize(1000); 

    // adding value to cache 
    cache.Add("#12","Jack"); 

    // searching value in cache 
    var flag = cache.LookUp("#12"); 
    if(flag) 
    { 
     Console.WriteLine("Found"); 
    } 

    // removing value 
    var value = cache.Remove("#12"); 

欲瞭解更多信息,您可以訪問:https://github.com/RishabKumar/CacheCrow

0

我寫LazyCache,使這個簡單,無痛爲可能的,同時還要確保只執行一次可緩存函數調用,即使兩個線程同時嘗試並緩存它們。

運行的軟件包管理器控制檯

PM> Install-Package LazyCache 

以下命令添加的命名空間,在你班上名列前茅

using LazyCache; 

現在緩存的東西:

// Create the cache - (in constructor or using dependency injection) 
IAppCache cache = new CachingService(); 

// Get products from the cache, or if they are not 
// cached then get from db and cache them, in one line 
var products = cache.GetOrAdd("get-products",() => dbContext.Products.ToList()); 

// later if you want to remove them 
cache.Remove("get-products"); 

查看更多在cache aside patternthe LazyCache docs

相關問題