寻找一个非常简单的Cache示例

Cas*_*ton 20 c# asp.net-mvc caching

我正在寻找一个简单的例子,说明如何将对象添加到缓存中,再次将其取回并删除它.

这里的第二个答案是我喜欢看的那种例子......

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

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

但是当我尝试这个时,我得到的第一行:

'Cache'是一种类型,在给定的上下文中无效.

在第三行,我得到:

非静态字段blah blah blah需要一个对象方法

所以,让我说我有List<T>......

var myList = GetListFromDB()
Run Code Online (Sandbox Code Playgroud)

现在我只想添加myList到缓存中,将其取出并删除它.

Yur*_*ian 18

.NET提供了一些Cache类

  • System.Web.Caching.Cache - ASP.NET中的默认缓存机制.您可以通过属性获取此类的实例,Controller.HttpContext.Cache也可以通过singleton获取它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();
      }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • System.Runtime.Caching.MemoryCache - 此类可以在用户代码中构造.它具有不同的界面和更多功能,如update\remove回调,区域,监视器等.要使用它,您需要导入库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
    
    Run Code Online (Sandbox Code Playgroud)

  • 好吧,MS说:https://docs.microsoft.com/en-us/dotnet/framework/performance/caching-in-net-framework-applications,建议使用RAM中的新应用程序MemoryCache命名空间. (3认同)
  • 现在他们建议使用 [Microsoft.Extensions.Caching.Memory](https://learn.microsoft.com/en-us/aspnet/core/performance/caching/memory#systemruntimecachingmemorycache) 而不是 System.Runtime.Caching.MemoryCache (3认同)

Mat*_*top 12

这是我过去做过的方式:

     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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

编辑:格式化.

顺便说一句,你可以做任何事情.我使用它与序列化结合来存储和检索150K项目的对象列表.


Kel*_*lly 8

如果你在这里使用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]);
Run Code Online (Sandbox Code Playgroud)


ala*_*ree 7

我编写 LazyCache 是为了使其尽可能简单、轻松,同时确保您只执行一次可缓存函数调用,即使两个线程尝试同时缓存它们也是如此。

在包管理器控制台中运行以下命令

PM> Install-Package LazyCache
Run Code Online (Sandbox Code Playgroud)

在类的顶部添加命名空间

using LazyCache;
Run Code Online (Sandbox Code Playgroud)

现在缓存东西:

// 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");
Run Code Online (Sandbox Code Playgroud)

请参阅有关缓存预留模式LazyCache 文档的更多信息