欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C# Cache緩存讀取的設(shè)置方法

 更新時間:2021年03月04日 10:00:22   作者:每天進步多一點  
這篇文章主要介紹了C# Cache緩存讀取的設(shè)置方法,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下

先創(chuàng)建一個CacheHelper.cs類,代碼如下:

using System;
using System.Web;
using System.Collections;
using System.Web.Caching;
  
public class CacheHelper
{
    /// <summary>
    /// 獲取數(shù)據(jù)緩存
    /// </summary>
    /// <param name="cacheKey">鍵</param>
    public static object GetCache(string cacheKey)
    {
        var objCache = HttpRuntime.Cache.Get(cacheKey);
        return objCache;
    }
    /// <summary>
    /// 設(shè)置數(shù)據(jù)緩存
    /// </summary>
    public static void SetCache(string cacheKey, object objObject)
    {
        var objCache = HttpRuntime.Cache;
        objCache.Insert(cacheKey, objObject);
    }
    /// <summary>
    /// 設(shè)置數(shù)據(jù)緩存
    /// </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>
    /// 移除指定數(shù)據(jù)緩存
    /// </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());
        }
    }
}

然后是調(diào)用:

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

 測試結(jié)果:

首次加載進來是為null,然后讀取數(shù)據(jù)庫,添加進緩存,當(dāng)前返回前臺的是從數(shù)據(jù)庫中取出的數(shù)據(jù)。

刷新頁面,發(fā)現(xiàn)緩存中已經(jīng)有了讀出的30條數(shù)據(jù),

然后接下來走,返回緩存中的數(shù)據(jù):

以上就是C# Cache緩存讀取的設(shè)置方法的詳細內(nèi)容,更多關(guān)于C# Cache緩存讀取的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論