時間就是金錢這道理大家都知道,但些事不見得人人都能有深刻的體認,對於擁有大量使用者的企業網站而言,只要能想辦法讓每個頁面減少一點點的系統負擔,那麼就可以相當幅度的降低運作成本。

以一個 Web-base 系統來說會產生成本的因素有幾項
  1. 網站的流量
  2. 商業邏輯的複雜運算
  3. 資料處理
  4. 系統安全防護

當使用者瀏覽一個從資料庫讀取數據後顯示在頁畫中的應用程式,在這一瞬間系統必需即時的對資料庫伺服器連結、讀取資料、運算及產生顯示頁面,這一切過程看似合理,但是如果有你有機會(時間)去好好檢視你曾經開發的系統,應該不難發現其實有很多的數據顯示不是非要那麼即時的,如果能夠在第一次讀取資料後就將資料 Cache 起來給接下來的數百甚至數千個使用者去瀏覽,直到有新的資料被更新才重新讀取,你將可以為系統節省了大量的資料庫連結及邏輯運算的成本。

在 ASP.NET 中 Cache 便提供了各種不同依賴方式的暫存,MSDN中有詳細說明:
  1. Key dependency
    以 key 值為依賴的暫存,你能把多個項目存入 Cache 中並且依賴指定的 key 值,當這個 key 值被移除了其相依賴的 Cache 項目也就失效。
  2. File dependency
    以檔案為依賴的暫存,你可以把 Cache 項目依賴指定的檔案,當檔案被修改或是刪除其相依賴的 Cache 項目也就失效。
  3. SQL dependency
    以資料庫中 Table 為依賴的暫存,當資料被更動其相依賴的 Cache 項目也就失效。
  4. Aggregate dependency
    An item in the cache is dependent on multiple elements through the use of the AggregateCacheDependency class. If any of the dependencies change, the item is removed from the cache.
  5. Custom dependency
    An item in the cache is configured with a dependency that you create in your own code. For example, you can create a custom Web service cache dependency that removes data from the cache when a call to a Web service results in a particular value.
夠了!! 我知道我英文很爛的事實終於被你發現了。

先不用擔心我在這裏長篇大論,我只想紹介簡單好用的方法來讓你思考如何改善系統效率,好好利用 Cache 的最大利益是可以節省系統資源(尤其是比較昂貴的資料庫存取),把曾經計算過的結果儲存下來再次使用。

首先是以檔案為依賴的暫存,第一次讀取檔案後將資料 Cache ,直到檔案被更改,這可大幅度的減少IO的存取動作,不必每次都去開檔讀檔也不必擔心檔案更新後沒有即時反應在系統中。

我們在物件中有一個Data的屬性,Data屬性的資料來自某個檔案....

 1public string Data  2{  3    get 4    {  5        ifthis.Cache["FileData"] == null)  6        {  7                string DataString =  ...... 在這裏讀取檔案 ...... ;  8 9               this.Cache.Insert("FileData",  10                         DataString ,  11                         new System.Web.Caching.CacheDependency(@"c:/File.txt"),  12                         System.Web.Caching.Cache.NoAbsoluteExpiration,  13                         System.Web.Caching.Cache.NoSlidingExpiration,  14                         System.Web.Caching.CacheItemPriority.High,  15                         null);  16        }  17 18        return (string)this.Cache["FileData"]  19    }  20}  

就這樣,直到 c:/File.txt 被更新 Cache 就會失效並且自動重新讀取。

另一個要講的是以時間為依賴的 Cache

 1public string Data  2{  3    get 4    {  5        ifthis.Cache["Data"] == null)  6        {  7              string SomeData = ........ 取得資料.......;  8 9            this.Cache.Insert("Data",  10                            SomeDate,  11                            null,  12                            DateTime.Now.AddSeconds(1200),  13                            System.Web.Caching.Cache.NoSlidingExpiration,  14                            System.Web.Caching.CacheItemPriority.High,  15                            null);  16        }  17 18        return (string)this.Cache["Data"]  19    }  20}  看不清楚 | 列印 | 複製


資料將以20分鐘為一個周期重新讀取。


OK! 結束了。
光是這樣的運用就可以有很棒的效果了,現在你可以好好的回頭檢視自已的系統是否也可以使用 .net 的 Cache ,雖然我明知道大部分的人並不會真的照著做..... 。