首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

Enterprise Library 實戰系列(十):快取應用程式區塊——進階篇

     編輯:關於.NET

一、基於時間的過期策略

1. 絕對時間

指定單一過期時間點:

DateTime refreshTime = new DateTime(2005, 11, 12, 12, 51, 30);
AbsoluteTime expireTime = new AbsoluteTime(refreshTime);
IsolatedCacheManager.Add("MyDataSet", ds, CacheItemPriority.Normal, null, expireTime);

使用 Cron-like 運算式(格式:分 時 日 月 週):

// 每週六 00:00 過期
ExtendedFormatTime expireTime = new ExtendedFormatTime("0 0 * * 6");
IsolatedCacheManager.Add("Key1", "Cache Item1", CacheItemPriority.Normal, null, expireTime);
  • * * * * *:每分鐘
  • 5 * * * *:每小時第 5 分鐘
  • * 21 * * *:每天 21:00
  • 31 15 * * *:每天 15:31
  • 7 4 * * 6:週六 04:07
  • 15 21 4 7 *:7 月 4 日 21:15

2. 相對時間

上次存取後經過指定間隔過期:

TimeSpan refreshTime = new TimeSpan(0, 5, 0); // 5 分鐘
SlidingTime expireTime = new SlidingTime(refreshTime);
IsolatedCacheManager.Add("Key1", "Cache Item1", CacheItemPriority.Normal, null, expireTime);

二、基於通知的過期策略(檔案相依性範例)

FileDependency expireNotice = new FileDependency("DependencyFile.txt");
myCacheManager.Add("FileKey", "String: Test Cache Item Dependency", 
    CacheItemPriority.Normal, null, expireNotice);

自訂過期類別需實作 ICacheItemExpiration 介面。

三、項目移除通知

觸發時機:過期、明確移除、清除策略執行。實作 ICacheItemRefreshAction 介面,若需後端儲存須標記 [Serializable]:

[Serializable]
public class ProductCacheRefreshAction : ICacheItemRefreshAction
{
    public void Refresh(string key, object expiredValue, CacheItemRemovedReason removalReason)
    {
        // 重新載入資料邏輯
    }
}

四、快取載入策略

1. 主動載入

應用程式啟動時預載。優點:執行期效能佳;缺點:啟動慢、可能浪費資源。適用:資料更新週期固定、生命週期明確、資源不穩定時。

CacheManager productsCache = CacheManager.GetCacheManager();
ArrayList list = dataProvider.GetProductList();
for (int i = 0; i < list.Count; i++)
{
    Product product = (Product)list[i];
    productsCache.Add(product.ProductID, product);
}

2. 被動載入

按需載入。優點:資源需求小;缺點:首次存取較慢。適用:狀態過多、資源不足、啟動期不想用快取。

CacheManager productsCache = CacheManager.GetCacheManager();
Product product = (Product)productsCache.GetData(productID);
if (product == null)
{
    product = dataProvider.GetProductByID(productID);
    if (product != null) productsCache.Add(productID, product);
}

五、快取清除

1. 明確清除

程式碼主動呼叫,可移除全部或特定項目。

2. 自動清除

由區塊依優先級與最後存取時間自動執行。組態設定:

  • MaximumElementsInCacheBeforeScavenging:觸發清除的最大項目數
  • NumberToRemoveWhenScavenging:每次清除項目數

優先級設定

for (int intCount = 0; intCount < 8; intCount++)
{
    string strKeyName = "Key" + intCount;
    if (intCount % 2 == 0)
        myCacheManager.Add(strKeyName, "High", CacheItemPriority.High, null, null);
    else
        myCacheManager.Add(strKeyName, "Low", CacheItemPriority.Low, null, null);
}

優先級:Low、Normal、High、NotRemovable。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved