C#中缓存的基本使用方法

2020-01-05 09:28:51刘景俊


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);
    int result = 0;
    //key的名字一定要确保请求的准确性 DataSource GetDataByDB 666缺一不可
    string key = "DataSource_GetDataByDB_666";
    if (CacheHelper.Exsits(key))
    {
     //缓存存在,直接获取原数据
     result = CacheHelper.Get<int>(key);
    }
    else
    {
     //缓存不存在,去生成缓存,并加入容器
     result = DataSource.GetDataByDB(666);
     CacheHelper.Add(key, result);
    }
    Console.WriteLine($"第{i}次请求获得的数据为:{result}");
   }
  }
 }
}

 3.3 我们看看加入缓存之后的效率如何

C#,缓存

四、可以看到,瞬间完成。事已至此,缓存的使用基本是完成了。但是回过头来我们想想看。一个系统成百上千个地方使用缓存的话,那岂不是要写成百上千个if else判断缓存是否存在,然后获取?

答案显而易见,肯定不合理的。所以我们要对代码进行优化。

4.1 缓存操作类(CacheHelper)编写一个通用的获取方法


/// <summary>
  /// 缓存获取方法
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="key">缓存字典容器对应key</param>
  /// <param name="func">委托方法 传入操作对象</param>
  /// <returns></returns>
  public static T GetCache<T>(string key, Func<T> func)
  {
   T t = default(T);
   if (CacheHelper.Exsits(key))
   {
    //缓存存在,直接获取原数据
    t = CacheHelper.Get<T>(key);
   }
   else
   {
    //缓存不存在,去生成缓存,并加入容器
    t = func.Invoke();
    CacheHelper.Add(key, t);
   }
   return t;
  }