Looking for a very simple Cache example

前端 未结 5 1961
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 13:51

I\'m looking for a real simple example of how to add an object to cache, get it back out again, and remove it.

The second answer here is the kind of example I\'d lov

相关标签:
5条回答
  • 2020-12-13 14:05

    Try this third party cache: CacheCrow, it is a simple LFU based cache.

    Install using powershell command in visual studio: Install-Package CacheCrow

    Code Snippet:

     // 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");
    

    For more information you can visit: https://github.com/RishabKumar/CacheCrow

    0 讨论(0)
  • 2020-12-13 14:18

    If your using MemoryCache here is a very simple example:

    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 讨论(0)
  • 2020-12-13 14:23

    Here is the way that I've done it in the past:

         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)
            };
             //remember to use the above created object as third parameter.
           _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>;
        }
    
        //Remove stuff from the cache. If no key supplied, all data will be erased.
        public static void RemoveItemsFromCache(_key)
        {
          if (string.IsNullOrEmpty(_key))
            {
                _cache.Dispose();
            }
            else
            {
                _cache.Remove(_key);
            }
        }
    

    EDIT: Formatting.

    BTW, you can do this with anything. I used this in conjunction with serialization to store and retrieve a 150K item List of objects.

    0 讨论(0)
  • 2020-12-13 14:24

    I wrote LazyCache to make this as simple and painless as possible, while also making sure you only execute your cacheable function calls once, even if two threads try and cache them at the same time.

    Run the following command in the Package Manager Console

    PM> Install-Package LazyCache
    

    Add the namespace at the top of you class

    using LazyCache;
    

    and now cache stuff:

    // 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");
    

    See more on the cache aside pattern or in the the LazyCache docs

    0 讨论(0)
  • 2020-12-13 14:27

    .NET provides a few Cache classes

    • System.Web.Caching.Cache - default caching mechanizm in ASP.NET. You can get instance of this class via property Controller.HttpContext.Cache also you can get it via singleton HttpContext.Current.Cache. This class is not expected to be created explicitly because under the hood it uses another caching engine that is assigned internally. To make your code work the simplest way is to do the following:

      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 - this class can be constructed in user code. It has the different interface and more features like update\remove callbacks, regions, monitors etc. To use it you need to import library System.Runtime.Caching. It can be also used in ASP.net application, but you will have to manage its lifetime by yourself.

      var cache = new System.Runtime.Caching.MemoryCache("MyTestCache");
      cache["ObjectList"] = list;                 // add
      list = (List<object>)cache["ObjectList"]; // retrieve
      cache.Remove("ObjectList");                 // remove
      
    0 讨论(0)
提交回复
热议问题