Application of Asp. Net Catch

Source: Internet
Author: User
Tags delete cache
Although it is already the broadband era, the kitten has gradually moved away from us. As WEB application developers, we still have the responsibility and obligation to continuously optimize the performance of WEB applications through technical means, this allows users to spend less time and more time browsing.
Fortunately, ASP. NET is based on. net Framework WEB development technology, it also enjoys.. Net Framework ,. net Framework provides us with a good Cache technology that enables us to develop WEB applications with faster speeds and better user experience. The namespace System. Web. Caching provides a Cache class. Its Cache Validity depends on the following three conditions:
1. time point (valid within the specified time point );
2. KEY value (the KEY value is marked as a Cache item );
3. file or directory (if the specified file or directory is changed, the original Cache item is unavailable );
Next I will share with you how to use Cache to Improve the Performance of ASP. NET applications.
During development, we often encounter reading the record list (for example, the Top N of the recently updated news list), recording itself (for example, a piece of news), and user access, is this information repeatedly read from the database? Smart users may know that this is completely unnecessary.

We designed a SiteCache class for ease of processing (using CSCache. CS in cs for reference) and provided several static methods to add and delete Cache items.

Code:
SiteCache. cs
1 using System;
2 using System. Collections;
3 using System. Text. RegularExpressions;
4 using System. Web;
5 using System. Web. Caching;
6
7 namespace 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 {
19 DayFactor = 17280;
20 HourFactor = 720;
21 MinuteFactor = 12;
22 Factor = 5;
23 _ cache = HttpRuntime. Cache;
24}
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 is mainly to maintain our own Cache items by using the features of the first and second aspects of Cache dependencies mentioned above.
With the SiteCache class, let's take a look at how to use it. Take reading the news TonN list as an example:

1 public 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 data directly from the database
14 CommonDataProvider dp = CommonDataProvider. Instance ();
15 newsSet = dp. GetNewsSetTopN (language, classCode, topN, orderBy, sortOrder );
16 // and Cache the result to HttpRuntime. Cache
17 SiteCache. Insert (cacheKey, newsSet, 60, CacheItemPriority. Normal );
18}
19
20}
21 return newsSet;
22}
 

In this way, you do not need to access the database again within five minutes to read the list. Of course, some people may ask what to do if a piece of news is deleted or modified within these five minutes, it doesn't matter. We can force Delete this Cache item based on the Cache KEY when deleting or modifying it. Of course, if you think you are not particularly concerned about the timeliness of the list, you do not need to force Delete this Cache item to automatically invalidate the time point defined by the Cache item. Of course, it is best to provide a method to forcibly Delete Cache items by matching items, for example:

 

1/** // <summary>
2 // Delete the Cache items in the matched NewsSetTopN list
3 /// </summary>
4 public 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

Call the static method ClearNewsSetTopNCache () after publishing the news to forcibly clear the original TopN cache items, for example:

 

1/** // <summary>
2 // publish (new) News
3 /// </summary>
4 /// <param name = "post"> News instance </param>
5 /// <returns> return status </returns>
6 public static int Create (News post)
7 {
8 int status;
9 CommonDataProvider dp = CommonDataProvider. Instance ();
10 dp. CreateUpdateDeleteNews (post, DataAction. Create, out status );
11 // forcibly clear matching cache items
12 ClearNewsSetTopNCache (post. Language, post. ClassCode, Globals. GetSiteSetting. NewsListTopN );
13 return status;
14}

That's all. If anything is wrong, I hope you can correct it.

Http://www.cnblogs.com/aspsir/archive/2006/07/27/461229.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.