Кэш Webforms ASP.NET был реализован очень удобно для временного хранения эксплуатационных данных. В первые годы платформы .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 (String, Object), который добавляет значение в кэш, подходит для большинства случаев, часто желательно применить различные настройки для кэширования данных на основе настройки веб -приложения, хранящихся в файле Web.Config, и иногда даже полностью отключение кэша для всего приложения. В этом случае исходный код не должен быть изменен, а приложение должно работать без перекомпиляции.
Кэш ASP.NET всегда возвращает экземпляры класса object , независимо от того, что такое фактический тип экземпляра. В большинстве случаев это не проблема, потому что вместо Value types можно использовать Nullable 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 ; Enum 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! Важно; максимальная ширина: 60%! Важно;} </style>