ASP.NET快取資料添加需求概述
ASP.NET使用緩衝機制,將需要大量伺服器資源來建立的Object Storage Service在記憶體中。緩衝這些類型的資源會大大改進應用程式的效能。緩衝是有Cache類實現的,可以通過對緩衝設定優先權CacheItemPriority枚舉值控制記憶體不夠時的“清理”優先順序。還可以為緩衝設定到期策略,以及為緩衝設定依賴項。
ASP.NET快取資料添加(將資料項目添加到緩衝中)
1、通過索引值對添加
- Cache["CacheItem"] = "Cached Item";
2、通過Insert 方法添加
Insert 方法向緩衝添加項,並且已經存在與現有項同名的項,則緩衝中的現有項將被替換。
- Cache.Insert("CacheItem", "Cached Item");
3、指定依賴項並添加(對添加到緩衝中的資料項目指定依賴項)
資料項目依賴一個字串數組對象的情況:
- string[] dependencies = { "Dependences" };
- Cache.Insert("CacheItem",
- "Cached Item",
- new System.Web.Caching.CacheDependency(null, dependencies));
資料項目依賴一個XML檔案的情況:
- Cache.Insert("CacheItem", "Cached Item",
- new System.Web.Caching.CacheDependency(
- Server.MapPath("XMLFile.xml")));
資料項目依賴多個依賴項的情況:
- 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、設定到期策略並添加
添加一分鐘絕對到期時間到緩衝中:
- Cache.Insert("CacheItem", "Cached Item",
- null, DateTime.Now.AddMinutes(1d),
- System.Web.Caching.Cache.NoSlidingExpiration);
添加10 分鐘彈性到期時間到緩衝中:
- Cache.Insert("CacheItem", "Cached Item",
- null, System.Web.Caching.Cache.NoAbsoluteExpiration,
- new TimeSpan(0, 10, 0));
5、設定優先權並添加
調用 Insert 方法,從 CacheItemPriority 枚舉中指定一個值。
- 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 方法,並且緩衝中已經存在與現有項同名的項,則該方法不會替換該項,並且不會引發異常。
- 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);