C# Cache緩存讀取設置


先創建一個CacheHelper.cs類,代碼如下:

using System;
using System.Web;
using System.Collections;
using System.Web.Caching;
 
public class CacheHelper
{
    /// <summary>
    /// 獲取數據緩存
    /// </summary>
    /// <param name="cacheKey">鍵</param>
    public static object GetCache(string cacheKey)
    {
        var objCache = HttpRuntime.Cache.Get(cacheKey);
        return objCache;
    }
    /// <summary>
    /// 設置數據緩存
    /// </summary>
    public static void SetCache(string cacheKey, object objObject)
    {
        var objCache = HttpRuntime.Cache;
        objCache.Insert(cacheKey, objObject);
    }
    /// <summary>
    /// 設置數據緩存
    /// </summary>
    public static void SetCache(string cacheKey, object objObject, int timeout = 7200)
    {
        try
        {
            if (objObject == null) return;
            var objCache = HttpRuntime.Cache;
            //相對過期
            //objCache.Insert(cacheKey, objObject, null, DateTime.MaxValue, timeout, CacheItemPriority.NotRemovable, null);
            //絕對過期時間
            objCache.Insert(cacheKey, objObject, null, DateTime.Now.AddSeconds(timeout), TimeSpan.Zero, CacheItemPriority.High, null);
        }
        catch (Exception)
        {
            //throw;
        }
    }
    /// <summary>
    /// 移除指定數據緩存
    /// </summary>
    public static void RemoveAllCache(string cacheKey)
    {
        var cache = HttpRuntime.Cache;
        cache.Remove(cacheKey);
    }
    /// <summary>
    /// 移除全部緩存
    /// </summary>
    public static void RemoveAllCache()
    {
        var cache = HttpRuntime.Cache;
        var cacheEnum = cache.GetEnumerator();
        while (cacheEnum.MoveNext())
        {
            cache.Remove(cacheEnum.Key.ToString());
        }
    }
}
 

然后是調用:

        public IEnumerable<CompanyModel> FindCompanys()
        {
            var cache = CacheHelper.GetCache("commonData_Company");//先讀取
            if (cache == null)//如果沒有該緩存
            {
                var queryCompany = _base.CompanyModel();//從數據庫取出
                var enumerable = queryCompany.ToList();
                CacheHelper.SetCache("commonData_Company", enumerable);//添加緩存
                return enumerable;
            }
            var result = (List<CompanyModel>)cache;//有就直接返回該緩存
            return result;
        }

 測試結果:

 

首次加載進來是為null,然后讀取數據庫,添加進緩存,當前返回前台的是從數據庫中取出的數據。

刷新頁面,發現緩存中已經有了讀出的30條數據,

然后接下來走,返回緩存中的數據:

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM