前言
是迁移以前的blog。
关于c# 缓存在web应用中的一个引导,能够建立起一个缓存的基本思路。
System.Web.Caching
这个真的是老生常谈了,我们只需要key和iv,然后我们就可以进行缓存了,非常的简单。
public List<ReRank> GetBoZhuRank(int category)
{
return CacheHelper.TryGet("GetBoZhuRank" + category, () =>
{
try
{
return new BLL.CastRoomApi(webEntity).GetCastRoomRankList(category).Data; //调用接口获取数据
}
catch (Exception ex)
{
LogUtlilty.WriteLog(string.Format("错误:{0}", ex.Message), LogUtlilty.Level.ERROR);
}
return new List<ReRank>();
}, DateTime.Now.AddMinutes(2), new List<ReRank>()); //缓存2分钟
}
下面我把这个帮助类也贴一下。
using System;
using System.Web;
using System.Collections;
namespace LiveCast.Web.Common.Utility
{
public class CacheHelper
{
/// <summary>
/// 获取数据缓存
/// </summary>
/// <param name="CacheKey">键</param>
public static object GetCache(string CacheKey)
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
return objCache[CacheKey];
}
/// <summary>
/// 设置数据缓存
/// </summary>
public static void SetCache(string CacheKey, object objObject)
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
objCache.Insert(CacheKey, objObject);
}
/// <summary>
/// 设置数据缓存
/// </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>
/// 设置数据缓存
/// </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>
/// 移除指定数据缓存
/// </summary>
public static void RemoveAllCache(string CacheKey)
{
System.Web.Caching.Cache _cache = HttpRuntime.Cache;
_cache.Remove(CacheKey);
}
/// <summary>
/// 移除全部缓存
/// </summary>
public static void RemoveAllCache()
{
System.Web.Caching.Cache _cache = HttpRuntime.Cache;
IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
while (CacheEnum.MoveNext())
{
_cache.Remove(CacheEnum.Key.ToString());
}
}
public static object Get(string key, Func<object> getValueFunc, DateTime absoluteExpiration)
{
var val = GetCache(key);
if (val == null)
{
val = getValueFunc();
if (val != null)
{
SetCache(key, val, absoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration);
}
}
return val;
}
public static TResult TryGet<TResult>(string key, Func<TResult> getValueFunc, DateTime absoluteExpiration, TResult defaultVal)
{
TResult result;
try
{
var val = Get(key, () => getValueFunc(), absoluteExpiration);
if (val == null)
{
val = defaultVal;
}
result = (TResult)val;
}
catch (Exception ex)
{
result = defaultVal;
LogUtlilty.WriteLog(string.Format("Cache中异常:{0}", ex.Message), LogUtlilty.Level.ERROR);
}
return result;
}
}
}
但是呢,我们可能会依赖于一些配置文件,姑且就这么说吧。
static void Main(string[] args)
{
//1.简单缓存,value可以是任何类型
HttpRuntime.Cache.Insert("mykey", "myvalue");
Console.WriteLine($"Key为mykey的缓存:{HttpRuntime.Cache["mykey"]}");
//2.使用缓存依赖项
string path = Path.Combine(Environment.CurrentDirectory, @"someCacheData.xml");
DataSet ds = new DataSet();
ds.ReadXml(path);
var cdy = new CacheDependency(path);
if (HttpRuntime.Cache.Get("myxml") == null)
{
//Dataset添加到缓存
System.Web.HttpRuntime.Cache.Insert("myxml", ds, cdy);
}
//从缓存中获取Dataset
for (var i = 1; i < 100; i++)
{
if (cdy.HasChanged)
{
System.Web.HttpRuntime.Cache.Insert("myxml", ds, cdy);
}
if (HttpRuntime.Cache.Get("myxml") == null)
{
DataSet ds1 = new DataSet();
ds1.ReadXml(path);
//Dataset添加到缓存
cdy = new CacheDependency(path);
System.Web.HttpRuntime.Cache.Insert("myxml", ds1, cdy);
}
DataSet resultDs = (DataSet)HttpRuntime.Cache.Get("myxml");
Console.WriteLine($"food下的f1节点:{resultDs.Tables["food"].Rows[0]["f1"]}");
Thread.Sleep(1000);
}
Console.ReadKey();
}
这其中的关键点在于CacheDependency,这个将会监听文件是否修改,如果修改那么缓存将会被清空,然后如果我们判断为空的时候,那么就重新加载配置。
注意当cdy.HasChanged 为true的时候,System.Web.HttpRuntime.Cache.Insert("myxml", ds1, cdy);是不会进行缓存的,你需要重新实例化一个对象。
system.runtime.cache
这东西更为强大,可以做一些回调,设置优先级。
static void Main(string[] args)
{
//缓存的配置
CacheItemPolicy policy = new CacheItemPolicy()
{
//缓存被删除是的回调
RemovedCallback = (arguments) => { Console.WriteLine($"缓存被移除的原因:{arguments.RemovedReason}"); },
//滑动过期时间
SlidingExpiration = TimeSpan.FromSeconds(5),
//绝对过期时间
//AbsoluteExpiration = DateTime.Now.AddSeconds(5),
//优先级有两种:Default,NotRemovable(不可移除)
Priority = System.Runtime.Caching.CacheItemPriority.NotRemovable
};
//添加缓存,key为mykey,值是myvalue ,
System.Runtime.Caching.MemoryCache.Default.Add("mykey", "myvalue", policy);
Console.WriteLine(MemoryCache.Default.Get("mykey"));
Thread.Sleep(6000);
Console.WriteLine(MemoryCache.Default.Get("mykey"));
Console.ReadKey();
}
redis等其他内存数据库缓存
请参考我的单独的redis 缓存系列,过于庞大。