ASP.NET WebForms 캐시는 작업 데이터를 임시로 유지하기 위해 매우 편리하게 구현되었습니다. .NET 플랫폼의 초기에 개발자는 종종 WinForms 응용 프로그램에서도 System.Web Namespace와 함께 작업하는 데 사용되었습니다.
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 과 유사합니다. 작은 웹 응용 프로그램을위한 간단하고 우아한 솔루션이지만 응용 프로그램이 자라면 키를 생성하기가 어려워집니다. 예를 들어, 공급 업체 및 모델과 같은 두 개의 관련 테이블을 캐싱하는 것이 좋습니다. 이 경우 Web Application은 모든 데이터 데이터 테이블에서 하나의 캐시 된 객체와 모델 테이블의 관련 레코드에 대한 많은 캐시 객체에 보관합니다. 공급 업체의 핵심은 Vendors 로 여겨지고 모델의 키는 Models.[VendorID] . 공급 업체 테이블이 변경되면 공급 업체의 캐시 된 인스턴스와 모델의 인스턴스 만 캐시에서 제거해야합니다. 이는 지역별로 캐시에서 데이터를 캐시하고 제거해야 함을 의미합니다.
설명 된 기능은 선택 사항이며 모든 웹 응용 프로그램에서 쉽게 구현할 수 있습니다. 프록시 템플릿은 설명 된 모든 기능을 구현하기위한 좋은 옵션입니다. 그 결과 라이브러리는 버전 2.0을 시작하는 모든 .NET 프레임 워크에서 사용할 수 있습니다. .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
}
}
} 질문이 있습니까? 저에게 연락하시면 정리할 수 있습니다.
<tyle> .inner {min-width : 800px! 중요; Max-Width : 60%! 중요;} </style>