(.net core 3.1)缓存基础篇–字典本地缓存
为了提高系统的性能,缓存是第一步。
其实在整个系统的流程中,每一个阶段都可以做缓存,浏览器可以缓存,cdn可以缓存,nginx代理也可以做缓存,但是大多数情况之下,在服务端做缓存那是必然的,今天搞一个基础版本,不用第三方。字典缓存。
缓存一定是第二次请求,或者是以上的请求
直接上代码
建立一个自定义缓存的帮助类 CustomCache
public class CustomCache
{
private static Dictionary<string, object> Cache = new Dictionary<string, object>();
#region 缓存基础版本
/// <summary>
/// 根据key得到 缓存value
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public static T GetCache<T>(string key)
{
T t = (T)default ;
if (Exist(key))
{
t = (T)Cache[key];
}
return t;
}
/// <summary>
/// 根据key 往字段里面添加value 生成缓存
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static void AddCache<T>(string key, T t)
{
Cache[key] = t;
}
/// <summary>
/// 判断 key在字段中是否有值
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static bool Exist(string key)
{
if (Cache.ContainsKey(key))
{
return true;
}
else
{
return false;
}
}
#endregion
#region 委托封装版本 ,减少代码重复
public static T GetCache<T>(string key, Func<T> func)
{
T t = (T)default;
if (Exist(key))
{
t = (T)Cache[key];
}
else{
t=func.Invoke();
Cache[key] = t;
}
return t;
}
#endregion
}
建立一个测试类 TestCacheDemo
public class TestCacheDemo
{
#region 缓存基础版本
public void TestCache(){
Console.WriteLine(DateTime.Now.ToString());
string key = "123456";
List<string> str= CustomCache.GetCache<List<string>>(key);
if (str==null)
{
///去往缓存里面增加数据
CustomCache.AddCache(key,Test()); //添加缓存的方法
}
Console.WriteLine(DateTime.Now.ToString());
}
#endregion
#region 委托封装版本 ,减少代码重复
public List<string> Test()
{
List<string> str = new List<string>();
for (int i = 0; i < 10_0000_0000; i++)
{
str.Add("1");
}
return str;
}
public void TestCache2()
{
Console.WriteLine(DateTime.Now.ToString());
string key = "123456";
CustomCache.GetCache<List<string>>(key, ()=> { return Test(); } );
Console.WriteLine(DateTime.Now.ToString());
}
#endregion
}
结果展示
代码讲解:先搞一个测试方法 Test(),循环十亿次,
第一次请求的时候呢调用 TestCache(),第一次肯定不会有缓存,所以很耗费时间,再次调用的时候呢 ,就直接会从字段里面去取值,所以从结果上来看,第二次请求反映相当的快。
代码封装,每次请求的时候呢,都会去判断是否有缓存,有的话直接从字典里面取值,所以呢,代码重复度太高,直接可以把请求的方法以委托的形式当做参数传入到得到缓存的方法 GetCache(string key, Func func) 里面
这样代码更少
关于缓存 还有过期的设定:永不过期,绝对过期,滑动过期
关于源数据和缓存数据不一定的问题,可以通过设置过期来解决,这里没有展现出代码
后面还会展示出关于redis和memcache第三方缓存机制,这两个使用其实更加方便是广泛