封装一个给 .NET Framework 用的内存缓存帮助类

image

前言

.NET Core 中已经内置了内存缓存相关的类和操作方法,直接就能使用,非常方便。但在 .NET Framework 中,如果想要使用内存缓存,需要自己进行封装。本文分享一个我自己项目中封装的内存缓存帮助类,有需要的童鞋可以拿去根据自己的实际业务修改修改,应用到自己的项目中。

代码

  1. 封装内存缓存类 CacheUtil

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.Caching;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Common.Util
    {
      public static class CacheUtil
      {
    	/// <summary>
    	/// <para>获取预定的缓存的过期时间</para>
    	/// <para>单位:小时</para>
    	/// </summary>
    	/// <returns></returns>
    	public static int GetCacheExpirationTime()
    	{
    	  // 默认过期时间是 2 小时
    	  int expiration = 2;
    	  
    	  // 从外部获取预定的缓存过期时间,如果有值,则将默认的过期时间改为外部设置的过期时间
    	  string cacheFile = Path.Combine(FileUtil.GetAppHomeBinPath(), "CacheExpiration.txt");
    	  Logger.DebugFormat("The cache expiration setting file is [{0}]", cacheFile);
    	  if (File.Exists(cacheFile))
    	  {
    		using (StreamReader sr = new StreamReader(new FileStream(cacheFile, FileMode.Open, FileAccess.Read)))
    		{
    		  var readBody = sr.ReadToEnd();
    		  int outExpiration = CommonUtil.GetObjTranNull<int>(readBody);
    		  if (outExpiration > 0) expiration = outExpiration;
    		}
    	  }
    	  Logger.DebugFormat("The cache expiration setting is [{0}] hours", expiration);
    	  return expiration;
    	}
    
    	/// <summary>
    	/// Set cache
    	/// </summary>
    	/// <param name="key"></param>
    	/// <param name="obj"></param>
    	/// <param name="expiration"></param>
    	public static void Set(string key, object obj, int expiration)
    	{
    	  var cache = MemoryCache.Default;
    	  var policy = new CacheItemPolicy
    	  {
    		AbsoluteExpiration = DateTime.Now.AddHours(expiration)
    	  };
    	  cache.Set(key, obj, policy);
    	}
    
    	/// <summary>
    	/// Get cach value by key
    	/// </summary>
    	/// <typeparam name="T"></typeparam>
    	/// <param name="key"></param>
    	/// <returns></returns>
    	public static T Get<T>(string key)
    	{
    	  try
    	  {
    		var cache = MemoryCache.Default;
    		var cacheVal = cache[key];
    		return CommonUtil.GetObjTranNull<T>(cacheVal);
    	  }
    	  catch (Exception ex)
    	  {
    		BDNALog.BDNALogger.DEFAULT.Warn("Error occurred when getting cache value: ", ex);
    		return default(T);
    	  }
    	}
    
    	/// <summary>
    	/// Check whether the cache item is exists by key
    	/// </summary>
    	/// <param name="key"></param>
    	/// <returns></returns>
    	public static bool IsKeyExists(string key)
    	{
    	  var cache = MemoryCache.Default;
    	  return cache.Contains(key);
    	}
      }
    }
    
  2. 使用

    // 1. 判断缓存在不在
    if (!CacheUtil.IsKeyExists("isNonInteractiveUser"))
    {
    	
    }
    
    // 2. 获取缓存的值
    string val = CacheUtil.Get<string>("isNonInteractiveUser");
    
    // 3. 设置缓存的值
    bool isNonInteractiveUser = true;
    int expiration = CacheUtil.GetCacheExpirationTime();
    CacheUtil.Set("isNonInteractiveUser", isNonInteractiveUser, expiration);
    

总结

使用这个封装好的内存缓存类,就可以方便地在 .NET Framework 中操作内存缓存了。

我是老杨,一个执着于编程乐趣、至今奋斗在一线的 10年+ 资深研发老鸟,是软件项目管理师,也是快乐的程序猿,持续免费分享全栈实用编程技巧、项目管理经验和职场成长心得。欢迎关注老杨的公众号,相互交流,共同进步!

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值