El caché ASP.NET WebForms se implementó muy convenientemente para mantener temporalmente los datos operativos. En los primeros años de la plataforma .NET, los desarrolladores a menudo solían trabajar con el espacio de nombres System.Web , incluso en las aplicaciones Winforms.
La plantilla de código, que se ofrece constantemente en artículos sobre el almacenamiento en caché de ASP.NET, es muy simple y práctica:
// 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 ] ;Sin embargo, la implementación de caché ASP.NET no incluye algunas características deseables.
Aunque el método Cache.insert (String, Object), que agrega un valor al caché, es adecuado para la mayoría de los casos, a menudo es deseable aplicar diferentes configuraciones para almacenar en caché los datos basados en la configuración de la aplicación web almacenada en el archivo web.config y, a veces, incluso desactivando completamente el caché para toda la aplicación. En este caso, el código fuente no debe cambiarse y la aplicación debe ejecutarse sin recompensar.
El caché ASP.NET siempre devuelve instancias de la clase object , sin importar cuál sea el tipo real de la instancia. En la mayoría de los casos, esto no es un problema, porque los Nullable types se pueden usar en lugar de los Value types . Quizás le gustaría tener métodos genéricos para recuperar datos del caché:
// 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" ) ; Si los métodos genéricos no están satisfechos para usted, entonces es posible usar la versión predeterminada. De hecho, estas dos opciones son idénticas. Pero los métodos genéricos ofrecen características adicionales. Por ejemplo, el valor predeterminado podría definirse si el caché no contiene un valor a recuperar:
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 */El caché ASP.NET siempre devuelve el objeto almacenado en el caché. Esto significa que los cambios en cualquier propiedad del objeto extraído también cambiarán el objeto almacenado en el caché, ya que estos son los mismos objetos. En algunos casos, es posible que desee modificar el objeto recuperado, pero deje el objeto en el caché sin cambios. Una de las funciones convenientes es recuperar una copia de un objeto del caché que se puede cambiar sin preocuparse por el objeto en el caché.
El caché ASP.NET es similar a un NameValueCollection . Es una solución simple y elegante para una pequeña aplicación web, pero se hace difícil generar las claves cuando la aplicación crece. Por ejemplo, considere almacenar en caché dos tablas relacionadas, como proveedores y modelos. En este caso, la aplicación web mantendrá todos los datos de la tabla de proveedores en un objeto almacenado en caché y muchos objetos en caché para registros asociados de la tabla de modelos. La clave para los proveedores que se supone que son Vendors y las claves para modelos que se supone que son Models.[VendorID] . Cuando la tabla de proveedores ha cambiado, la instancia en caché para los proveedores y solo las instancias asociadas para los modelos deben eliminarse del caché. Esto significa que los datos deben almacenarse en caché y eliminar de la caché por regiones.
Las funciones descritas son opcionales y se pueden implementar fácilmente en cualquier aplicación web. La plantilla Proxy es una buena opción para implementar todas las características descritas. La biblioteca resultada se puede usar en todos los marcos .NET, iniciando la versión 2.0. El .NET Framework 4.0 presenta el espacio de nombres System.Runtime.Caching y varias clases con un nuevo modelo de almacenamiento en caché. Por lo tanto, no se requiere usar el caché ASP.NET estándar y sus mejoras.
Triste pero verdadero.
/// <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 define cómo almacenar objetos en el caché
/// <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
}
}
} Si desea definir la configuración de tiempo que sean diferentes de las especificadas de forma predeterminada en la memoria caché, use uno de los métodos 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
}
}
} ¿Tiene preguntas? Contáctame y te ayudaré a resolverlo.
<syle> .inner {min-width: 800px! IMPORTANTE; Max-Width: 60%! IMPORTANTE;} </style>