二、编写一个缓存操作类
2.1 构造一个字典型容器,用于存放缓存数据,权限设为private ,防止随意访问造成数据不安全性
//缓存容器
private static Dictionary<string, object> CacheDictionary = new Dictionary<string, object>();
2.2 构造三个方法(添加数据至缓存容器、从缓存容器获取数据、判断缓存是否存在)
/// <summary>
/// 添加缓存
/// </summary>
public static void Add(string key, object value)
{
CacheDictionary.Add(key, value);
}
/// <summary>
/// 获取缓存
/// </summary>
public static T Get<T>(string key)
{
return (T)CacheDictionary[key];
}
/// <summary>
/// 判断缓存是否存在
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static bool Exsits(string key)
{
return CacheDictionary.ContainsKey(key);
}
三、程序入口编写测试方法
3.1 先看一下普通情况不适用缓存,它的执行效率有多慢
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cache
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i < 6; i++)
{
Console.WriteLine($"------第{i}次请求------");
int result = DataSource.GetDataByDB(666);
Console.WriteLine($"第{i}次请求获得的数据为:{result}");
}
}
}
}
3.2 接下来,我们编写缓存试用方法。概念无非就是根据key前往字典容器里查找是否有相对应缓存数据,有则直接调用,没有则生成并存入字典容器里。











