تم تنفيذ ذاكرة التخزين المؤقت لـ ASP.NET WebForms بشكل مريح للغاية للحفاظ على البيانات التشغيلية. في السنوات الأولى من منصة .NET ، غالبًا ما يستخدم المطورون للعمل مع مساحة اسم System.Web ، حتى في تطبيقات WinForms.
قالب الكود ، الذي يتم تقديمه باستمرار في مقالات حول التخزين المؤقت لـ 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 لا يتضمن بعض الميزات المرغوبة.
على الرغم من أن طريقة cache.insert (السلسلة ، الكائن) ، تضيف قيمة إلى ذاكرة التخزين المؤقت ، تكون مناسبة لمعظم الحالات ، فغالبًا ما يكون من المستحسن أن تطبق إعدادات مختلفة لتخزين بيانات التخزين المؤقت بناءً على إعدادات تطبيق الويب المخزنة في ملف الويب. في هذه الحالة ، لا ينبغي تغيير رمز المصدر ويجب تشغيل التطبيق دون إعادة تجميع.
تقوم ذاكرة التخزين المؤقت 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 . إنه حل بسيط وأنيق لتطبيق ويب صغير ، ولكن يصبح من الصعب إنشاء المفاتيح عند نمو التطبيق. على سبيل المثال ، فكر في تخزين المؤقتة الجداول ذات الصلة ، مثل البائعين والنماذج. في هذه الحالة ، سيحتفظ تطبيق الويب بجميع البيانات من جدول البائعين في كائن مخبأ واحد والعديد من الكائنات المخزنة مؤقتًا للسجلات المرتبطة بجدول النماذج. مفتاح البائعين الذين من المفترض أن يكونوا Vendors ومفاتيح النماذج المفترض أن تكون Models.[VendorID] . عندما يتغير جدول البائعين ، يجب إزالة المثيل المخزنة مؤقتًا للبائعين والحالات المرتبطة فقط بالنماذج من ذاكرة التخزين المؤقت. هذا يعني أنه يجب تخزين البيانات مؤقتًا وإزالتها من ذاكرة التخزين المؤقت حسب المناطق.
الوظائف الموصوفة اختيارية ويمكن تنفيذها بسهولة في أي تطبيق ويب. قالب الوكيل هو خيار جيد لتنفيذ جميع الميزات الموصوفة. يمكن استخدام المكتبة الناتجة على جميع أطر عمل .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-width: 800px! مهم ؛ Max-Width: 60 ٪! مهم ؛} </style>