Hướng dẫn Cache trong .Net tăng tốc độ load trang ko phải call database nhiều

0
47
5/5 - (2 bình chọn)

Bạn đang code C# .NET mà đang vướng phần tối ưu tốc độ load trang thì đây là giải pháp có thể giúp bạn. Hiện có 2 cách mình đã dùng và thấy nó hiệu quả. Bạn thử dùng xem thế nào nhé

1. Cache từng phần của trang

public string AddCacheContent(bool BypassCache, string strCacheKey, string strCacheContent, int CacheFromMinutes)
{
string cacheKey = strCacheKey;
object cacheItem = Cache[cacheKey] as string;
if ((BypassCache) || (cacheItem == null))
{
cacheItem = strCacheContent;
Cache.Insert(cacheKey, cacheItem, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(CacheFromMinutes));
}
return (string)cacheItem;
}

public string GetCacheContent( string strCacheKey)
{
string cacheKey = strCacheKey;
object cacheItem = Cache[cacheKey] as string; 
return (string)cacheItem;
}

public bool CheckCacheContent(string strCacheKey)
{
string cacheKey = strCacheKey;
object cacheItem = Cache[cacheKey] as string;
if (cacheItem == null)
{
return false;

}
return true;
}

 

2. Cache toàn trang

Response.AddCacheItemDependency(“key”);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(200)); Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
Response.Cache.SetValidUntilExpires(true);

3. Cache bằng việc đọc ghi file

(phần này mình xin phép update sau nhé)

 

 

Theo dõi
Thông báo của
guest
0 Góp ý
Phản hồi nội tuyến
Xem tất cả bình luận