ASP.NET緩存數(shù)據(jù)添加方法一覽
ASP.NET緩存數(shù)據(jù)添加需求概述
ASP.NET使用緩存機(jī)制,將需要大量服務(wù)器資源來創(chuàng)建的對象存儲在內(nèi)存中。緩存這些類型的資源會大大改進(jìn)應(yīng)用程序的性能。緩存是有Cache類實(shí)現(xiàn)的,可以通過對緩存設(shè)置優(yōu)先級CacheItemPriority枚舉值控制內(nèi)存不夠時(shí)的“清理”優(yōu)先順序。還可以為緩存設(shè)置過期策略,以及為緩存設(shè)置依賴項(xiàng)。
ASP.NET緩存數(shù)據(jù)添加(將數(shù)據(jù)項(xiàng)添加到緩存中)
1、通過鍵值對添加
- Cache["CacheItem"] = "Cached Item";
2、通過Insert 方法添加
Insert 方法向緩存添加項(xiàng),并且已經(jīng)存在與現(xiàn)有項(xiàng)同名的項(xiàng),則緩存中的現(xiàn)有項(xiàng)將被替換。
- Cache.Insert("CacheItem", "Cached Item");
3、指定依賴項(xiàng)并添加(對添加到緩沖中的數(shù)據(jù)項(xiàng)指定依賴項(xiàng))
數(shù)據(jù)項(xiàng)依賴一個(gè)字符串?dāng)?shù)組對象的情況:
- string[] dependencies = { "Dependences" };
- Cache.Insert("CacheItem",
- "Cached Item",
- new System.Web.Caching.CacheDependency(null, dependencies));
數(shù)據(jù)項(xiàng)依賴一個(gè)XML文件的情況:
- Cache.Insert("CacheItem", "Cached Item",
- new System.Web.Caching.CacheDependency(
- Server.MapPath("XMLFile.xml")));
數(shù)據(jù)項(xiàng)依賴多個(gè)依賴項(xiàng)的情況:
- System.Web.Caching.CacheDependency dep1 =
- new System.Web.Caching.CacheDependency(Server.MapPath("XMLFile.xml"));
- string[] keyDependencies2 = { "CacheItem1" };
- System.Web.Caching.CacheDependency dep2 =
- new System.Web.Caching.CacheDependency(null, keyDependencies2);
- System.Web.Caching.AggregateCacheDependency aggDep =
- new System.Web.Caching.AggregateCacheDependency();
- aggDep.Add(dep1);
- aggDep.Add(dep2);
- Cache.Insert("CacheItem", "Cached Item", aggDep);
4、設(shè)置過期策略并添加
添加一分鐘絕對過期時(shí)間到緩存中:
- Cache.Insert("CacheItem", "Cached Item",
- null, DateTime.Now.AddMinutes(1d),
- System.Web.Caching.Cache.NoSlidingExpiration);
添加10 分鐘彈性過期時(shí)間到緩存中:
- Cache.Insert("CacheItem", "Cached Item",
- null, System.Web.Caching.Cache.NoAbsoluteExpiration,
- new TimeSpan(0, 10, 0));
5、設(shè)置優(yōu)先級并添加
調(diào)用 Insert 方法,從 CacheItemPriority 枚舉中指定一個(gè)值。
- Cache.Insert("CacheItem", "Cached Item",
- null, System.Web.Caching.Cache.NoAbsoluteExpiration,
- System.Web.Caching.Cache.NoSlidingExpiration,
- System.Web.Caching.CacheItemPriority.High, null);
6、通過Add方法添加
Add 方法將返回您添加到緩存中的對象。另外,如果使用 Add 方法,并且緩存中已經(jīng)存在與現(xiàn)有項(xiàng)同名的項(xiàng),則該方法不會替換該項(xiàng),并且不會引發(fā)異常。
- string CachedItem = (string)Cache.Add("CacheItem",
- "Cached Item", null,
- System.Web.Caching.Cache.NoAbsoluteExpiration,
- System.Web.Caching.Cache.NoSlidingExpiration,
- System.Web.Caching.CacheItemPriority.Default,
- null);
以上就介紹了ASP.NET緩存數(shù)據(jù)添加的六種方法。本文來自菩提屋:《緩存應(yīng)用程序數(shù)據(jù)(一)》
【編輯推薦】