C# Cache緩存讀取的設(shè)置方法
先創(chuàng)建一個(gè)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;
//相對(duì)過(guò)期
//objCache.Insert(cacheKey, objObject, null, DateTime.MaxValue, timeout, CacheItemPriority.NotRemovable, null);
//絕對(duì)過(guò)期時(shí)間
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)//如果沒(méi)有該緩存
{
var queryCompany = _base.CompanyModel();//從數(shù)據(jù)庫(kù)取出
var enumerable = queryCompany.ToList();
CacheHelper.SetCache("commonData_Company", enumerable);//添加緩存
return enumerable;
}
var result = (List<CompanyModel>)cache;//有就直接返回該緩存
return result;
}
測(cè)試結(jié)果:

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

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

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

以上就是C# Cache緩存讀取的設(shè)置方法的詳細(xì)內(nèi)容,更多關(guān)于C# Cache緩存讀取的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#創(chuàng)建WCF服務(wù)控制臺(tái)應(yīng)用程序詳解
這篇文章主要為大家詳細(xì)介紹了C#創(chuàng)建WCF服務(wù)控制臺(tái)應(yīng)用程序,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07
FtpHelper實(shí)現(xiàn)ftp服務(wù)器文件讀寫(xiě)操作(C#)
這篇文章主要為大家詳細(xì)介紹了FtpHelper實(shí)現(xiàn)ftp服務(wù)器文件讀寫(xiě)操作,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-03-03
關(guān)于C#中使用Oracle存儲(chǔ)過(guò)程返回結(jié)果集的問(wèn)題
Oracle中可以使用游標(biāo)(Cursor)對(duì)數(shù)據(jù)集進(jìn)行操作,但在存儲(chǔ)過(guò)程輸出參數(shù)中直接使用Cursor錯(cuò)誤,下面小編給大家?guī)?lái)了C#中使用Oracle存儲(chǔ)過(guò)程返回結(jié)果集的問(wèn)題,感興趣的朋友一起看看吧2021-10-10
C#實(shí)現(xiàn)簡(jiǎn)單的計(jì)算器小功能
這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)簡(jiǎn)單的計(jì)算器小功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01

