[英]Data Caching in ASP.Net
我需要從一些參考數據中填寫一些下拉框。 即城市列表,國家列表等。我需要填寫各種網絡表格。 我認為,我們應該在我們的應用程序中緩存這些數據,這樣我們就不會在每個表單上都有數據庫。 我是緩存和ASP.Net的新手。 請建議我如何做到這一點。
我總是將以下類添加到我的所有項目中,這使我可以輕松訪問Cache對象。 按照Hasan Khan的回答實現這一點將是一個很好的方法。
public static class CacheHelper
{
/// <summary>
/// Insert value into the cache using
/// appropriate name/value pairs
/// </summary>
/// <typeparam name="T">Type of cached item</typeparam>
/// <param name="o">Item to be cached</param>
/// <param name="key">Name of item</param>
public static void Add<T>(T o, string key, double Timeout)
{
HttpContext.Current.Cache.Insert(
key,
o,
null,
DateTime.Now.AddMinutes(Timeout),
System.Web.Caching.Cache.NoSlidingExpiration);
}
/// <summary>
/// Remove item from cache
/// </summary>
/// <param name="key">Name of cached item</param>
public static void Clear(string key)
{
HttpContext.Current.Cache.Remove(key);
}
/// <summary>
/// Check for item in cache
/// </summary>
/// <param name="key">Name of cached item</param>
/// <returns></returns>
public static bool Exists(string key)
{
return HttpContext.Current.Cache[key] != null;
}
/// <summary>
/// Retrieve cached item
/// </summary>
/// <typeparam name="T">Type of cached item</typeparam>
/// <param name="key">Name of cached item</param>
/// <param name="value">Cached value. Default(T) if item doesn't exist.</param>
/// <returns>Cached item as type</returns>
public static bool Get<T>(string key, out T value)
{
try
{
if (!Exists(key))
{
value = default(T);
return false;
}
value = (T)HttpContext.Current.Cache[key];
}
catch
{
value = default(T);
return false;
}
return true;
}
}
從你的其他問題我讀到你正在使用帶有dal,業務和表示層的3層架構。
所以我假設你有一些數據訪問類。 理想的做法是擁有相同類的緩存實現並在其中進行緩存。
例如:如果你有一個接口IUserRepository,那么UserRepository類將實現它並通過方法在db中添加/刪除/更新條目然后你也可以有CachedUserRepository,它將包含UserRepository對象的實例,在get方法上它將首先查看緩存一些鍵(從方法參數派生),如果找到該項,那么它將返回它,否則你在內部對象上調用該方法; 得到數據; 添加到緩存然后返回它。
您的CachedUserRepository顯然也會有緩存對象的實例。 有關如何使用Cache對象的詳細信息,請查看http://msdn.microsoft.com/en-us/library/18c1wd61(v=vs.85).aspx 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.