[. Net Object-Oriented programming advanced] (15) caching (Cache) (2) Using Cache to improve program performance and javacache caching

Source: Internet
Author: User

[. Net Object-Oriented programming advanced] (15) caching (Cache) (2) Using Cache to improve program performance and javacache caching

[. Net Object-Oriented programming advanced] (15) Cache (ii) using Cache to improve program performance

This section introduces:

In the previous section, the cache technology exchanges space for time, and introduces the Client Cache and two common server la S. This section mainly introduces one.. NET. use Cache to improve program performance.

1. Cache namespace

. NET has two namespaces for caching.

Namespace 1: System. Web. Caching

Namespace 2: System. Runtime. Caching

Reference scope:Both namespaces can be referenced in Web and non-WEB applications.

Lifecycle:In theory, it always exists. We can set the expiration time. However, when the memory overhead is insufficient, the cache is cleared to release space. Therefore, the subsequent application will determine whether the Cache object exists. If it does not exist, re-create it to solve the failure problem.

The following describes how to use the cache.

2. Create and read Cache

Cache is also intended for objects. We should first create an entity class, or a familiar "martial arts master" class:

/// <Summary> /// class: martial arts master /// MartialArtsMaster /// </summary> public class MartialArtsMaster {/// <summary> /// No. /// </summary> public int id {get; set ;}//< summary> /// name /// </summary> public string name {get; set ;} /// <summary> /// martial // </summary> public string menpai {get; set ;} /// <summary> /// wugong /// </summary> public string kongFu {get; set ;}}

Next we will create a cache, read the cache, and traverse the object.

// Add several martial arts masters List <MartialArtsMaster> masterList = new List <MartialArtsMaster> () {new MartialArtsMaster () {id = 1, name = "Duan Yu ", menpai = "tianlong Temple", kongFu = ""}, new MartialArtsMaster () {id = 2, name = "Qiao Feng", menpai = "", kongFu = ""}, new MartialArtsMaster () {id = 3, name = "", menpai = "", kongFu =" "}}; // cache creation System. web. caching. cache objCache = HttpRuntime. cache; objCache. insert ("MyCache", masterList); // read the cache (objCache ["MyCache"] as List <MartialArtsMaster> ). forEach (m => Console. writeLine ("name:" + m. name + "School:" + m. menpai + ":" + m. kongFu ));

The running result is as follows:

3. Common application of cache in factory reflection mode

We will not discuss the design mode here, but when using many code generators, cache technology is often used to dynamically create multiple data layer interfaces in the factory reflection mode, cache the classes created by dynamic reflection to improve the next access efficiency.

The following is the cache application code snippet in the simple factory reflection mode:

Object objType = GetCache (ClassName); // read from the cache if (objType = null) {try {objType = Assembly. load (AssemblyPath ). createInstance (ClassName); // reflection to create SetCache (ClassNamespace, objType); // write cache} catch (Exception ex ){}}

4. Cache Usage principles

The cache effectively improves the program efficiency, but it should also be used properly. The following are several usage principles:

First, data may be frequently used and can be cached.

Second, the Access frequency of data is very high, or the access frequency of a data is not high, but it has a long life cycle, so it is best to cache such data.

Third, in Asp.net, if the cache is too large, a memory overflow error is reported, especially when the DataSet object is large.

Make proper use of the service based on actual conditions. For example, if the cache is used too much, it will increase the pressure on the server. The entire page output cache will affect data updates. If you really need to cache a large amount of data, you can consider static technology.

5. General Cache

Finally, we will sort out a common cache class for our friends to call.

Namespace: KaJiMao. Common

Class Name: CacheHelper

File Name:CacheHelper. Cs 

Using System; using System. web; using System. collections; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace KaJiMao. common {/// <summary> /// Cache generic class /// Yubinfeng /// Date: public class CacheHelper {// <summary> // obtain the data cache /// </summary> /// <param name = "CacheKey"> key </param> public static object GetCache (string CacheKey) {System. web. caching. cache objCache = HttpRuntime. cache; return objCache [CacheKey];} // <summary> // set the data Cache /// </summary> public static void SetCache (string CacheKey, object objObject) {System. web. caching. cache objCache = HttpRuntime. cache; objCache. insert (CacheKey, objObject) ;}/// <summary> /// set the data cache /// </summary> public static void SetCache (string CacheKey, object objObject, timeSpan Timeout) {System. web. caching. cache objCache = HttpRuntime. cache; objCache. insert (CacheKey, objObject, null, DateTime. maxValue, Timeout, System. web. caching. cacheItemPriority. notRemovable, null);} // <summary> // set the data cache // </summary> public static void SetCache (string CacheKey, object objObject, DateTime absoluteExpiration, timeSpan slidingExpiration) {System. web. caching. cache objCache = HttpRuntime. cache; objCache. insert (CacheKey, objObject, null, absoluteExpiration, slidingExpiration );} /// <summary> /// remove the specified data cache /// </summary> public static void RemoveAllCache (string CacheKey) {System. web. caching. cache _ cache = HttpRuntime. cache; _ cache. remove (CacheKey) ;}/// <summary> /// Remove all caches /// </summary> public static void RemoveAllCache () {System. web. caching. cache _ cache = HttpRuntime. cache; IDictionaryEnumerator CacheEnum = _ cache. getEnumerator (); while (CacheEnum. moveNext () {_ cache. remove (CacheEnum. key. toString ());}}}}View Code

========================================================== ========================================================== ====================

 Returned directory

<If it is helpful to you, please click here for recommendations. If yesDo not understand or make a mistakePoints, Please exchange more>

<If you have any difficulty reading this series of articles, please read. net Object-Oriented Programming basics first>

<Reprinted statement: technology requires a spirit of sharing. You are welcome to repost the article in this blog, but please note the copyright and URL>

. NET exchange group: 467189533

========================================================== ========================================================== ====================

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.