First create a CacheHelper.cs class with the following code :
- using System;
- using System.Web;
- using System.Collections;
- using System.Web.Caching;
- public class CacheHelper
- {
- /// <summary>
- /// Get the data cache
- /// </summary>
- /// <param name="cacheKey">键</param>
- public static object GetCache(string cacheKey)
- {
- var objCache = HttpRuntime.Cache.Get(cacheKey);
- return objCache;
- }
- /// <summary>
- /// Set up the data cache
- /// </summary>
- public static void SetCache(string cacheKey, object objObject)
- {
- var objCache = HttpRuntime.Cache;
- objCache.Insert(cacheKey, objObject);
- }
- /// <summary>
- /// Set up the data cache
- /// </summary>
- public static void SetCache(string cacheKey, object objObject, int timeout = 7200)
- {
- try
- {
- if (objObject == null) return;
- var objCache = HttpRuntime.Cache;
- //relatively expired
- //objCache.Insert(cacheKey, objObject, null, DateTime.MaxValue, timeout, CacheItemPriority.NotRemovable, null);
- //absolute expiration time
- objCache.Insert(cacheKey, objObject, null, DateTime.Now.AddSeconds(timeout), TimeSpan.Zero, CacheItemPriority.High, null);
- }
- catch (Exception)
- {
- //throw;
- }
- }
- /// <summary>
- /// Remove the specified data cache
- /// </summary>
- public static void RemoveAllCache(string cacheKey)
- {
- var cache = HttpRuntime.Cache;
- cache.Remove(cacheKey);
- }
- /// <summary>
- /// Remove all caches
- /// </summary>
- public static void RemoveAllCache()
- {
- var cache = HttpRuntime.Cache;
- var cacheEnum = cache.GetEnumerator();
- while (cacheEnum.MoveNext())
- {
- cache.Remove(cacheEnum.Key.ToString());
- }
- }
- }
The citations are also posted above, just a few.
Then call:
- public IEnumerable<CompanyModel> FindCompanys()
- {
- var cache = CacheHelper.GetCache( "commonData_Company"); //Read first
- if (cache == null) //if there is no such cache
- {
- var queryCompany = _base.CompanyModel(); //fetch from database
- var enumerable = queryCompany.ToList();
- CacheHelper.SetCache( "commonData_Company", enumerable); //Add cache
- return enumerable;
- }
- var result = (List<CompanyModel>)cache; //Return to the cache directly if there is one
- return result;
- }
The test results are also posted here to see:
The first load is null, and then the database is read and added to the cache. The current return to the foreground is the data taken from the database.
Refresh the page and find that there are already 30 pieces of data read out in the cache,
Then go ahead and return the data in the cache:
roughly these.
End