我正在寻找一个真正的简单示例,说明如何将对象添加到缓存,再次将其取出并删除。
这里的第二个答案是我希望看到的例子......
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
添加到缓存中,将其取出并删除。
NET 提供了一些缓存类
System.Web.Caching.Cache - ASP.NET 中的默认缓存机制。您可以通过属性获取此类的实例
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
这是我过去的做法:
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);
}
}
编辑:格式化。
顺便说一句,你可以用任何东西来做到这一点。我将其与序列化结合使用,以存储和检索 150K 项的对象列表。
如果你使用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]);
我编写了 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");
查看有关缓存端模式或 LazyCache 文档的更多信息
试试这个第三方缓存: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