Cache WebForms ASP.NET diimplementasikan dengan sangat nyaman untuk menjaga data operasional sementara. Pada tahun -tahun awal platform .NET, pengembang sering digunakan untuk bekerja dengan System.Web namespace, bahkan dalam aplikasi WinForms.
Template kode, yang terus -menerus ditawarkan dalam artikel tentang caching ASP.NET, sangat sederhana dan praktis:
// 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 ] ;Namun, implementasi cache ASP.NET tidak termasuk beberapa fitur yang diinginkan.
Meskipun metode Cache.insert (String, Object), yang menambahkan nilai ke dalam cache, cocok untuk sebagian besar kasus, seringkali diinginkan untuk mengajukan pengaturan yang berbeda untuk caching data berdasarkan pengaturan aplikasi web yang disimpan dalam file web.config, dan kadang -kadang bahkan menonaktifkan cache untuk seluruh aplikasi. Dalam hal ini, kode sumber tidak boleh diubah dan aplikasi harus berjalan tanpa mengkompilasi ulang.
Cache ASP.NET selalu mengembalikan contoh kelas object , tidak peduli apa jenis instance yang sebenarnya. Dalam kebanyakan kasus, ini bukan masalah, karena Nullable types dapat digunakan sebagai pengganti Value types . Mungkin Anda ingin memiliki metode generik untuk mengambil data dari cache:
// 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" ) ; Jika metode generik tidak terpenuhi untuk Anda, maka dimungkinkan untuk menggunakan versi default. Bahkan, kedua opsi ini identik. Tetapi metode generik menawarkan fitur tambahan. Misalnya, nilai default dapat ditentukan jika cache tidak berisi nilai yang akan diambil:
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 */Cache ASP.NET selalu mengembalikan objek yang disimpan dalam cache. Ini berarti bahwa perubahan pada properti apa pun dari objek yang diekstraksi juga akan mengubah objek yang disimpan dalam cache, karena ini adalah objek yang sama. Dalam beberapa kasus, Anda mungkin ingin memodifikasi objek yang diambil, tetapi tinggalkan objek di cache yang tidak berubah. Salah satu fungsi yang nyaman adalah mengambil salinan objek dari cache yang dapat diubah tanpa khawatir tentang objek dalam cache.
Cache ASP.NET mirip dengan NameValueCollection . Ini adalah solusi sederhana dan elegan untuk aplikasi web kecil, tetapi menjadi sulit untuk menghasilkan kunci saat aplikasi tumbuh. Misalnya, pertimbangkan caching dua tabel terkait, seperti vendor dan model. Dalam hal ini aplikasi web akan menyimpan semua data dari tabel vendor dalam satu objek yang di -cache dan banyak objek yang di -cache untuk catatan terkait dari tabel model. Kunci untuk vendor yang seharusnya menjadi Vendors dan kunci untuk model yang seharusnya menjadi Models.[VendorID] . Ketika tabel vendor telah berubah, instance cache untuk vendor dan hanya instance terkait untuk model harus dihapus dari cache. Ini berarti bahwa data harus di -cache dan dihapus dari cache berdasarkan daerah.
Fungsi yang dijelaskan bersifat opsional dan dapat dengan mudah diimplementasikan dalam aplikasi web apa pun. Template proxy adalah pilihan yang baik untuk mengimplementasikan semua fitur yang dijelaskan. Perpustakaan yang dihasilkan dapat digunakan pada semua kerangka kerja .NET, mulai versi 2.0. .NET Framework 4.0 memperkenalkan System.Runtime.Caching namespace dan beberapa kelas dengan model caching baru. Oleh karena itu, menggunakan cache asp.net standar dan perbaikannya tidak diperlukan.
Sedih tapi benar.
/// <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 ; Enum CacheExpirationType mendefinisikan cara menyimpan objek di cache
/// <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
}
}
} Jika Anda ingin mendefinisikan pengaturan waktu yang berbeda dari yang ditentukan secara default dalam cache, gunakan salah satu metode 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
}
}
} Memiliki pertanyaan? Hubungi saya dan saya akan membantu Anda menyelesaikannya.
<tyle> .inner {Min-width: 800px! Penting; Max-Width: 60%! Penting;} </style>