Although we are now in the broadband era and kittens have gradually left us, as WEB application developers, we still have the responsibility and obligation to continuously optimize WEB application performance through technical means so that users can wait less while browsing. More refreshing.
Fortunately, ASP.NET, as a WEB development technology based on .Net Framework, also enjoys the advantages of .Net Framework. .Net Framework provides us with good Cache technology, allowing us to develop faster, user-friendly Experience better WEB applications. The namespace System.Web.Caching provides the Cache class, the effectiveness of which depends on the following three situations:
1. Time point (valid within the specified time point);
2. KEY value (KEY value is used as Cache item identifier);
3. File or directory (if the specified file or directory changes, the original Cache item will not be available);
Next, I will share with you how to use Cache to improve the performance of ASP.NET applications based on actual developed applications.
In development, we often encounter the problem of reading the record list (such as the recently updated news list Top N) and the record itself (such as a piece of news). When the user accesses, does such information need to be read repeatedly from the database every time? Woolen cloth? If you are smart, you may know that this is completely unnecessary.
In order to facilitate processing, we might as well design a SiteCache class (drawing lessons from CSCache.cs in CS) and provide several static methods to handle the addition and deletion of Cache items.
Code:
SiteCache.cs
1using System;
2using System.Collections;
3using System.Text.RegularExpressions;
4using System.Web;
5using System.Web.Caching;
6
7namespace Ycweb.Components
8{
9 public class SiteCache
10 {
11 private static readonly Cache _cache;
12 public static readonly int DayFactor;
13 private static int Factor;
14 public static readonly int HourFactor;
15 public static readonly int MinuteFactor;
16
17 static SiteCache()
18 {
19DayFactor = 17280;
20 HourFactor = 720;
21 MinuteFactor = 12;
22 Factor = 5;
23 _cache = HttpRuntime.Cache;
twenty four }
25
26 private SiteCache()
27 {
28 }
29
30 public static void Clear()
31 {
32 IDictionaryEnumerator enumerator = _cache.GetEnumerator();
33 while (enumerator.MoveNext())
34 {
35 _cache.Remove(enumerator.Key.ToString());
36}
37 }
38
39 public static object Get(string key)
40 {
41 return _cache[key];
42 }
43
44 public static void Insert(string key, object obj)
45 {
46 Insert(key, obj, null, 1);
47 }
48
49 public static void Insert(string key, object obj, int seconds)
50 {
51 Insert(key, obj, null, seconds);
52 }
53
54 public static void Insert(string key, object obj, CacheDependency dep)
55 {
56 Insert(key, obj, dep, HourFactor*12);
57 }
58
59 public static void Insert(string key, object obj, int seconds, CacheItemPriority priority)
60 {
61 Insert(key, obj, null, seconds, priority);
62 }
63
64 public static void Insert(string key, object obj, CacheDependency dep, int seconds)
65 {
66 Insert(key, obj, dep, seconds, CacheItemPriority.Normal);
67 }
68
69 public static void Insert(string key, object obj, CacheDependency dep, int seconds, CacheItemPriority priority)
70 {
71 if (obj != null)
72 {
73 _cache.Insert(key, obj, dep, DateTime.Now.AddSeconds((double) (Factor*seconds)), TimeSpan.Zero, priority, null);
74}
75 }
76
77 public static void Max(string key, object obj)
78 {
79 Max(key, obj, null);
80}
81
82 public static void Max(string key, object obj, CacheDependency dep)
83 {
84 if (obj != null)
85 {
86 _cache.Insert(key, obj, dep, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.AboveNormal, null);
87 }
88}
89
90 public static void MicroInsert(string key, object obj, int secondFactor)
91 {
92 if (obj != null)
93 {
94 _cache.Insert(key, obj, null, DateTime.Now.AddSeconds((double) (Factor*secondFactor)), TimeSpan.Zero);
95 }
96 }
97
98 public static void Remove(string key)
99 {
100 _cache.Remove(key);
101 }
102
103 public static void RemoveByPattern(string pattern)
104 {
105 IDictionaryEnumerator enumerator = _cache.GetEnumerator();
106 Regex regex1 = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
107 while (enumerator.MoveNext())
108 {
109 if (regex1.IsMatch(enumerator.Key.ToString()))
110 {
111 _cache.Remove(enumerator.Key.ToString());
112 }
113 }
114 }
115
116 public static void ReSetFactor(int cacheFactor)
117 {
118 Factor = cacheFactor;
119 }
120
121
122
123 }
124}
In fact, this class mainly uses the first and second features of Cache dependencies mentioned above to maintain our own Cache items.
Now that we have the SiteCache class, let's see how to use it. Or take reading the news TonN list as an example:
1public static RecordSet GetNewsSetTopN(string classCode,int topN,SortPostsBy orderBy, SortOrder sortOrder, string language)
2{
3 string cacheKey = string.Format("NewsSetTopN-LG:{0}:CC:{1}:TN:{2}:OB:{3}:SO:{4}", language,classCode,topN.ToString( ), orderBy.ToString(),sortOrder.ToString());
4
5 //Read cache items from context
6 RecordSet newsSet = HttpContext.Current.Items[cacheKey] as RecordSet;
7 if (newsSet == null)
8 {
9 //Read cache items from HttpRuntime.Cache
10 newsSet = SiteCache.Get(cacheKey) as RecordSet;
11 if (newsSet == null)
12 {
13 //Read directly from the database
14 CommonDataProvider dp=CommonDataProvider.Instance();
15 newsSet =dp.GetNewsSetTopN(language,classCode,topN,orderBy,sortOrder);
16 //And cache the results in HttpRuntime.Cache
17 SiteCache.Insert(cacheKey, newsSet, 60, CacheItemPriority.Normal);
18}
19
20}
21return newsSet;
twenty two}
In this way, there is no need to repeatedly access the database to read the list within 5 minutes. Of course, some people will ask, what if a certain news item is deleted or modified within these 5 minutes? It doesn’t matter. We can delete or modify it. Forcefully delete the Cache item based on the Cache KEY. Of course, if you feel that you don't particularly care about the timeliness of the list, you can not forcefully delete the Cache item and let the Cache item automatically expire at the time defined. Of course, it is best to provide a method to forcibly delete Cache items based on matching pattern items, for example:
1/**//// <summary>
2/// Delete the Cache items of the matching NewsSetTopN list
3/// </summary>
4public static void ClearNewsSetTopNCache(string language,string classCode,int topN)
5{
6 string cacheKey = string.Format("NewsSetTopN-LG:{0}:CC:{1}:TN:{2}",language,classCode,topN.ToString());
7 SiteCache.RemoveByPattern(cacheKey);
8}
9.
After publishing the news, call the static method ClearNewsSetTopNCache() to forcefully clear the original TopN cache items, for example:
1/**//// <summary>
2/// Publish (new) news
3/// </summary>
4/// <param name="post">News example</param>
5/// <returns>Return status</returns>
6public static int Create(News post)
7{
8 int status;
9 CommonDataProvider dp=CommonDataProvider.Instance();
10 dp.CreateUpdateDeleteNews(post, DataAction.Create, out status);
11 //Force clear matching cache items
12 ClearNewsSetTopNCache (post.Language, post.ClassCode,Globals.GetSiteSetting.NewsListTopN);
13 return status;
14}
That's all. If there is anything wrong, I hope all colleagues will correct me.
http://www.cnblogs.com/aspsir/archive/2006/07/27/461229.html