ASP.NET WebForms緩存非常方便地用於臨時保留操作數據。在.NET平台的早期,即使在Winforms應用程序中,開發人員也經常使用System.Web名稱空間。
關於ASP.NET緩存文章中不斷提供的代碼模板非常簡單且實用:
// try to get an instance of object from cache
DataSet ds = HttpRuntime . Cache [ "KeyName" ] as DataSet ;
// check the result and recreate it, if it is null
if ( ds == null )
{
ds = QueryDataFromDatabase ( ) ;
HttpRuntime . Cache . Insert ( "KeyName" , ds ) ;
}
// using the instance of object that has been populated from cache or from storage
DataRow dr = ds . Tables [ 0 ] . Rows [ 0 ] ;但是,ASP.NET緩存實現不包括一些理想的功能。
儘管在緩存中添加值的CACH.INSERT(字符串,對象)方法適用於大多數情況,但通常需要根據Web.config文件中存儲的Web應用程序的設置為緩存數據進行不同的設置,有時甚至完全將緩存功能完全禁用於整個應用程序。在這種情況下,不應更改源代碼,並且在不重新編譯的情況下運行應用程序。
無論該實例的實際類型是什麼,ASP.NET緩存總是返回object類的實例。在大多數情況下,這不是問題,因為可以使用Nullable types代替Value types 。也許您想擁有從緩存中檢索數據的通用方法:
// this is a dafault extraction data from cache
myClassName item = HttpRuntime . Cache [ "Key1" ] as myClassName ;
// this is a desired extraction data with generic methods
myClassName item = DataCache . Get < myClassName > ( "Key1" ) ; 如果不滿足您的通用方法,則可以使用默認版本。實際上,這兩個選擇是相同的。但是通用方法提供了其他功能。例如,如果緩存不包含要檢索的值,則可以定義默認值:
myClassName defaultValue = new myClassName ( /* init properties */ ) ;
myClassName item = DataCache . Get < myClassName > ( "Key1" , defaultValue ) ;
/* if there is nothing in the cache, then the item will be defaultValue */ASP.NET緩存總是返回存儲在緩存中的對象。這意味著更改提取的對象的任何屬性也將更改存儲在緩存中的對象,因為這些對像是相同的對象。在某些情況下,您可能需要修改檢索到的對象,但將對象留在緩存中。方便的功能之一是從高速緩存中檢索對象的副本,該副本可以更改,而不必擔心緩存中的對象。
ASP.NET緩存類似於NameValueCollection 。對於小型Web應用程序來說,這是簡單而優雅的解決方案,但是當應用程序長大時,很難生成鑰匙。例如,考慮緩存兩個相關表,例如供應商和模型。在這種情況下,Web應用程序將在一個緩存的對像中將所有數據保留在供應商表中,以及許多緩存對象,用於模型表的關聯記錄。供應商的鑰匙應該是Vendors ,而應該是Models.[VendorID] 。當供應商表已更改後,供應商的緩存實例,僅需從緩存中刪除模型的相關實例。這意味著應通過區域將數據緩存並從緩存中刪除。
所述功能是可選的,可以在任何Web應用程序中輕鬆實現。代理模板是實現所有描述的功能的好選擇。所得的庫可用於所有.NET框架,即啟動版2.0。 .NET Framework 4.0介紹了System.Runtime.Caching名稱空間和具有新的緩存模型的幾個類。因此,不需要使用標準ASP.NET緩存及其改進。
悲傷但真實。
/// <summary>
/// Is cache used or not
/// </summary>
public static bool IsCacheEnable ;
/// <summary>
/// How to store objects in the cache
/// </summary>
public static CacheExpirationType ExpirationType ;
/// <summary>
/// How long objects should be stored in the cache
/// </summary>
public static TimeSpan ExpirationTime ;枚舉CacheExpirationType定義瞭如何將對象存儲在緩存中
/// <summary>
/// How to store objects in the cache
/// </summary>
public enum CacheExpirationType
{
/// <summary>
/// Without time limit, the value of the <seealso cref = "DataCache.ExpirationTime" /> property will be ignored
/// </summary>
NoExpiration ,
/// <summary>
/// The <seealso cref="DataCache.ExpirationTime"/> at which the inserted object expires and is removed from the cache
/// </summary>
AbsoluteExpiration ,
/// <summary>
/// The interval <seealso cref="DataCache.ExpirationTime"/> between the time the inserted object is last accessed and the time at which that object expires
/// </summary>
SlidingExpiration
} /// <summary>
/// Retrieves the specified item from the Cache object
/// </summary>
/// <typeparam name="T">The type for the cache item to retrieve</typeparam>
/// <param name="key">The identifier for the cache item to retrieve</param>
/// <param name="defaultValue">The default value if the object is not in the cache</param>
/// <returns>The retrieved cache item, or <paramref name="defaultValue"/> if the key is not found</returns>
public static T GetData < T > ( string key , T defaultValue = default ( T ) )
/// <summary>
/// Retrieves the deep copied of specified item from the Cache object
/// </summary>
/// <typeparam name="T">The type for the cache item to retrieve</typeparam>
/// <param name="key">The identifier for the cache item to retrieve</param>
/// <param name="defaultValue">The default value if the object is not in the cache</param>
/// <returns>The retrieved cache item, or <paramref name="defaultValue"/> if the key is not found</returns>
public static T GetDeepCopiedData < T > ( string key , T defaultValue = default ( T ) ) /// <summary>
/// Inserts an item into the cache with a cache key to reference its location, using default values provided by the settings
/// </summary>
/// <param name="key">The cache key used to reference the item</param>
/// <param name="value">The object to be inserted into the cache</param>
public static void InsertData ( string key , object value )
/// <summary>
/// Inserts an item into the cache with a cache key to reference its location, using the absolute expiration time
/// </summary>
/// <param name="key">The cache key used to reference the item</param>
/// <param name="value">The object to be inserted into the cache</param>
/// <param name="expirationTime">How long the object should be stored in the cache</param>
public static void InsertAbsoluteExpirationData ( string key , object value , TimeSpan expirationTime )
/// <summary>
/// Inserts an item into the cache with a cache key to reference its location, using the sliding expiration time
/// </summary>
/// <param name="key">The cache key used to reference the item</param>
/// <param name="value">The object to be inserted into the cache</param>
/// <param name="expirationTime">How long the object should be stored in the cache</param>
public static void InsertSlidingExpirationData ( string key , object value , TimeSpan expirationTime )
/// <summary>
/// Inserts an item into the cache with a cache key to reference its location, using the type of expiration and default value for expiration time
/// </summary>
/// <param name="key">The cache key used to reference the item</param>
/// <param name="value">The object to be inserted into the cache</param>
/// <param name="expirationType">How to store objects in the cache</param>
public static void InsertExpirationData ( string key , object value , CacheExpirationType expirationType )
/// <summary>
/// Inserts an item into the cache with a cache key to reference its location, using the type of expiration and expiration time
/// </summary>
/// <param name="key">The cache key used to reference the item</param>
/// <param name="value">The object to be inserted into the cache</param>
/// <param name="expirationType">How to store objects in the cache</param>
/// <param name="expirationTime">How long the object should be stored in the cache</param>
public static void InsertExpirationData ( string key , object value , CacheExpirationType expirationType , TimeSpan expirationTime ) /// <summary>
/// Removes the specified item from the application's cache
/// </summary>
/// <param name="key">An identifier for the cache item to remove</param>
public static void RemoveDataByKey ( string key )
/// <summary>
/// Removes all items from the application's cache that starts with key
/// </summary>
/// <param name="keyStartsWith">An starts with identifier for the cache item to remove</param>
public static void RemoveAllDataByKey ( string keyStartsWith )
/// <summary>
/// Removes all items from the application's cache
/// </summary>
public static void RemoveAllData ( ) public class Global : System . Web . HttpApplication
{
protected void Application_Start ( object sender , EventArgs e )
{
Settings settings = Settings . Default ;
DataCache . IsCacheEnable = settings . IsCacheEnable ;
DataCache . ExpirationType = settings . ExpirationType ;
DataCache . ExpirationTime = settings . ExpirationTime ;
}
} public partial class DefaultPage : System . Web . UI . Page
{
public const string STR_CACHENAME = "something" ;
protected void Page_Load ( object sender , EventArgs e )
{
if ( ! this . IsPostBack )
{
SomethingDataModel val = DataCache . GetData < SomethingDataModel > ( STR_CACHENAME ) ;
if ( val == null )
{
SomethingDataModel val = new SomethingDataModel ( ) ; // get data from ...
DataCache . InsertData ( STR_CACHENAME , val ) ;
}
DataBind ( val ) ; // use data on the page
}
}
}如果要定義與默認情況下指定的時間設置不同的時間設置,請使用覆蓋的Insert{Which}Data方法之一。
public partial class DefaultPage : System . Web . UI . Page
{
public const string STR_CACHENAME = "something" ;
protected void Page_Load ( object sender , EventArgs e )
{
if ( this . IsPostBack )
{
DAL . Update ( ) ; // update the database ...
DataCache . RemoveAllDataByKey ( STR_CACHENAME ) ; // clear cache
Response . Redirect ( "Default.aspx" ) ; // proccessing the request
}
}
} 有疑問?與我聯繫,我將幫助您解決。
<style> .inner {min寬度:800px!最大寬度:60%!重要;} </style>