1.简介
服务器本地缓存是使用一个静态字典,根据唯一准确描述缓存的key来将值存入内存中
新建一个CustomCache类,用来保存缓存
代码如下:
using System; using System.Collections.Generic; namespace ceshi { class CustomCache { private static Dictionary<string, object> CustomCacheDictionary = new Dictionary<string, object>(); public static void Add(string key,object value)//添加缓存 { CustomCacheDictionary.Add(key,value); } public static T GetT<T>(string key)//获取缓存的值 { return (T)CustomCacheDictionary[key]; } public static bool Exsits(string key)//判断缓存是否存在 { return CustomCacheDictionary.ContainsKey(key); } } }
Program:
using System; using System.Threading.Tasks; using System.Threading; namespace ceshi { class Program { static void Main(string[] args) { for (int i = 0; i < 5; i++) { string key = "add_key_101";//唯一准确描述缓存的key int result; if (CustomCache.Exsits(key)) { result = CustomCache.GetT<int>(key); } else {
//----------------调用模拟函数--------------- result = Simulation(); //----------------添加缓存------------------- CustomCache.Add(key, result); } Console.WriteLine(result); } Console.Read(); } static int Simulation() { //-------------模拟获取数据的时耗-------------- int result; Thread.Sleep(2000); Random random = new Random(); result = random.Next(0, 100); return result; } } }
2.封装调用函数
现实羡慕中缓存是无处不在的,所以为了方便使用缓存,可以将上面红色字体的代码封装到CustomCache里面,以方便调用
CustomCache类添加一个函数:
using System; using System.Collections.Generic; namespace ceshi { class CustomCache { private static Dictionary<string, object> CustomCacheDictionary = new Dictionary<string, object>(); public static void Add(string key,object value) { CustomCacheDictionary.Add(key,value); } public static T GetT<T>(string key) { return (T)CustomCacheDictionary[key]; } public static bool Exsits(string key) { return CustomCacheDictionary.ContainsKey(key); } public static T GetDataT<T>(string key,Func<T> func)//委托Func是无参有返回值 { T result = default(T); if(Exsits(key)) { result=(T)CustomCacheDictionary[key]; } else { result=func.Invoke();//实例化外部模拟获取数据的函数,也就是运行这个函数并接收返回值 Add(key, result); } return result; } } }
Program:
using System; using System.Threading.Tasks; using System.Threading; namespace ceshi { class Program { static void Main(string[] args) { for (int i = 0; i < 5; i++) { string key = "add_key_101";//唯一准确描述缓存的key int result; result=CustomCache.GetDataT<int>(key, () => Simulation()); Console.WriteLine(result); } Console.Read(); } static int Simulation() { //-------------模拟获取数据的时耗-------------- int result; Thread.Sleep(2000); Random random = new Random(); result = random.Next(0, 100); return result; } } }
这样在多次调用时可以节省很多代码量。