想提升站点的性能,于是增加了缓存,但是站点不会太大,于是不会到分布式memcached的缓存和redis这个nosql库,于是自己封装了.NET内置的缓存组件

原先使用System.Web.Caching.Cache,但是asp.net会在System.Web.Caching.Cache缓存页面等数据,于是替换了System.Web.Caching.Cache为MemoryCache。

而在使用MemoryCache的时候,重新启动网站会丢失缓存,于是加了自己的扩展,将缓存序列化存放在文件内,在缓存丢的时候从文件内获取缓存,做了简易的扩展。(现在应用在我的Cactus里面)

using System;
using System.Collections;
using System.Web;
using System.Text;
using System.IO;
using System.Runtime.Caching;
using System.Diagnostics;
using System.Runtime.Serialization.Formatters.Binary;
using System.Configuration;
using System.Collections.Generic;namespace Cactus.Common
{/// <summary>/// 缓存对象数据结构/// </summary>
    [Serializable()]public class CacheData{public object Value { get;set;}public DateTime CreateTime { get; set; }public DateTimeOffset AbsoluteExpiration { get; set; }public DateTime FailureTime { get { if (AbsoluteExpiration == System.Runtime.Caching.ObjectCache.InfiniteAbsoluteExpiration) {return AbsoluteExpiration.DateTime;} else { return CreateTime.AddTicks(AbsoluteExpiration.Ticks); } } }public CacheItemPriority Priority { get; set; }}/// <summary>/// 缓存处理类(MemoryCache)/// </summary>public class CacheHelper{//在应用程序的同级目录(主要防止外部访问)public static string filePath = Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory + ConfigurationManager.ConnectionStrings["filecache"].ConnectionString);//文件扩展名public static string fileExt = ".cache";/// <summary>/// 获取数据缓存/// </summary>/// <param name="cacheKey">键</param>public static object GetCache(string cacheKey){//System.Web.Caching.Cache objCache = HttpRuntime.Cache;//return objCache[cacheKey];long i=System.Runtime.Caching.MemoryCache.Default.GetCount();CacheItem objCache=System.Runtime.Caching.MemoryCache.Default.GetCacheItem(cacheKey);if (objCache == null){string _filepath = filePath + cacheKey + fileExt;if (File.Exists(_filepath)){FileStream _file = File.OpenRead(_filepath);if (_file.CanRead){Debug.WriteLine("缓存反序列化获取数据:" + cacheKey);object obj = CacheHelper.BinaryDeSerialize(_file);CacheData _data = (CacheData)obj;if (_data != null){//判断是否过期if (_data.FailureTime >= DateTime.Now){//将数据添加到内存
                                CacheHelper.SetCacheToMemory(cacheKey, _data);return _data.Value;}else{Debug.WriteLine("数据过期:" + cacheKey);File.Delete(_filepath);//数据过期return null;}}else { return null; }}else { return null; }}else { return null; }}else {CacheData _data = (CacheData)objCache.Value;return _data.Value;}}/// <summary>/// 内存缓存数/// </summary>/// <returns></returns>public static object GetCacheCount(){return System.Runtime.Caching.MemoryCache.Default.GetCount();}/// <summary>/// 文件缓存数/// </summary>/// <returns></returns>public static object GetFileCacheCount(){DirectoryInfo di = new DirectoryInfo(filePath);return di.GetFiles().Length;}/// <summary>/// 设置数据缓存/// </summary>public static bool SetCache(string cacheKey, object objObject, CacheItemPolicy policy){//System.Web.Caching.Cache objCache = HttpRuntime.Cache;            //objCache.Insert(cacheKey, objObject);string _filepath = filePath + cacheKey + fileExt;if (Directory.Exists(filePath)==false) {Directory.CreateDirectory(filePath);}//设置缓存数据的相关参数CacheData data = new CacheData() { Value = objObject, CreateTime = DateTime.Now, AbsoluteExpiration = policy.AbsoluteExpiration, Priority = policy.Priority };CacheItem objCache = new CacheItem(cacheKey, data);FileStream stream = null;if (File.Exists(_filepath) == false){stream = new FileStream(_filepath, FileMode.CreateNew, FileAccess.Write, FileShare.Write);}else {stream = new FileStream(_filepath, FileMode.Create, FileAccess.Write, FileShare.Write);}Debug.WriteLine("缓存序列化设置数据:" + cacheKey);CacheHelper.BinarySerialize(stream, data);return System.Runtime.Caching.MemoryCache.Default.Add(objCache, policy);}public static bool SetCacheToMemory(string cacheKey, CacheData data){CacheItemPolicy policy = new CacheItemPolicy();CacheItem objCache = new CacheItem(cacheKey, data);policy.AbsoluteExpiration = data.AbsoluteExpiration;policy.Priority = CacheItemPriority.NotRemovable;return System.Runtime.Caching.MemoryCache.Default.Add(objCache, policy);}public static bool SetCache(string cacheKey, object objObject, DateTimeOffset AbsoluteExpiration){//System.Web.Caching.Cache objCache = HttpRuntime.Cache;            //objCache.Insert(cacheKey, objObject);CacheItemPolicy _priority = new CacheItemPolicy();_priority.Priority = CacheItemPriority.NotRemovable;_priority.AbsoluteExpiration = AbsoluteExpiration;return SetCache(cacheKey, objObject, _priority);}public static bool SetCache(string cacheKey, object objObject, CacheItemPriority priority){//System.Web.Caching.Cache objCache = HttpRuntime.Cache;            //objCache.Insert(cacheKey, objObject);CacheItemPolicy _priority = new CacheItemPolicy();_priority.Priority = priority;_priority.AbsoluteExpiration = System.Runtime.Caching.ObjectCache.InfiniteAbsoluteExpiration;return SetCache(cacheKey, objObject, _priority);}/// <summary>/// 设置数据缓存/// </summary>public static bool SetCache(string cacheKey, object objObject){//System.Web.Caching.Cache objCache = HttpRuntime.Cache;//objCache.Insert(cacheKey, objObject, null, DateTime.MaxValue, timeout, System.Web.Caching.CacheItemPriority.NotRemovable, null);return CacheHelper.SetCache(cacheKey, objObject, System.Runtime.Caching.CacheItemPriority.NotRemovable);}/// <summary>/// 移除指定数据缓存/// </summary>public static void RemoveCache(string cacheKey){//System.Web.Caching.Cache cache = HttpRuntime.Cache;//cache.Remove(cacheKey);
            System.Runtime.Caching.MemoryCache.Default.Remove(cacheKey);string _filepath = filePath + cacheKey + fileExt;File.Delete(_filepath);}/// <summary>/// 移除全部缓存/// </summary>public static void RemoveAllCache(){//System.Web.Caching.Cache cache = HttpRuntime.Cache;//IDictionaryEnumerator cacheEnum = cache.GetEnumerator();//while (cacheEnum.MoveNext())//{//    cache.Remove(cacheEnum.Key.ToString());//}MemoryCache _cache = System.Runtime.Caching.MemoryCache.Default;foreach (var _c in _cache.GetValues(null)){_cache.Remove(_c.Key);}DirectoryInfo di = new DirectoryInfo(filePath);di.Delete(true);}/// <summary>/// 清除指定缓存/// </summary>/// <param name="type">1:内存 2:文件</param>public static void RemoveAllCache(int type){if (type == 1) {MemoryCache _cache = System.Runtime.Caching.MemoryCache.Default;foreach (var _c in _cache.GetValues(null)){_cache.Remove(_c.Key);}} else if (type == 2){DirectoryInfo di = new DirectoryInfo(filePath);di.Delete(true);} }#region 流序列化public static void BinarySerialize(Stream stream, object obj){try{stream.Seek(0, SeekOrigin.Begin);BinaryFormatter formatter = new BinaryFormatter();formatter.Serialize(stream, obj);}catch (Exception e){IOHelper.WriteDebug(e);}finally{//stream.Close();
                stream.Dispose();}}public static object BinaryDeSerialize(Stream stream){object obj = null;stream.Seek(0, SeekOrigin.Begin);try{BinaryFormatter formatter = new BinaryFormatter();obj = formatter.Deserialize(stream);}catch (Exception e){IOHelper.WriteDebug(e);}finally{//stream.Close();
                stream.Dispose();}return obj;}#endregion}
}

转载于:https://www.cnblogs.com/RainbowInTheSky/p/5557936.html

缓存处理类(MemoryCache结合文件缓存)相关推荐

  1. php数据库缓存类,常见php数据文件缓存类汇总

    本文实例汇总了常见php数据文件缓存类.分享给大家供大家参考.具体分析如下: 数据文件缓存的做法我们常用的有php文件缓存与利用memcache来缓存数据,下面面我分别总结了memcache缓存数据与 ...

  2. 如何防止android app被误删除,如何避免手机清理缓存时误删了重要文件【注意事项】...

    如何避免手机清理缓存时误删了重要文件? 缓存只是内存中少部分数据的复制品,所以CPU到缓存中寻找数据时,也会出现找不到的情况(因为这些数据没有从内存复制到缓存中去),这时CPU还是会到内存中去找数据, ...

  3. 行车记录仪 - 录像 - 文件缓存

    背景 基于ffmpeg实现录像功能,性能不理想,前后路摄像头视频码率相加只有28Mbps加上音频也只有4MB/s左右,使用class 10的sd卡 + 2秒 ringbuffer缓存的情况下,依然出现 ...

  4. 不错php文件缓存类,一个不错的PHP文件页面缓存类

    [导读]在php中缓存分类数据库缓存,文件缓存和内存缓存,下面我来给各位同学详细介绍PHP文件缓存类实现代码,有需要了解的朋友可参考.页面缓存类 代码如下复制代码 在 缓存分类数据库缓存,文件缓存和内 ...

  5. php mysql文件缓存_PHP文件缓存类实现代码

    php中缓存分类数据库缓存,文件缓存和内存缓存,下面我来给各位同学详细介绍PHP文件缓存类实现代码,有需要了解的朋友可参考. 页面缓存类 代码如下 : /*include( "cache.p ...

  6. php 高效缓存类,简单高效的文件缓存php类

    简单高效的文件缓存php类 class FileCache { public $keyPrefix = ''; public $cachePath = ''; public $cacheFileSuf ...

  7. 自写保存字符串或文件为asp.net缓存的类

    using System; using System.Text; using System.Web; using System.IO; namespace Chsword {     /// < ...

  8. 【opencart3源码分析】文件缓存类file.php

    <?php namespace Session; /*** 文件缓存类* @package Session*/ class File {private $directory;// 读取缓存pub ...

  9. 【Laravel3.0.0源码阅读分析】文件缓存类file.php

    <?php namespace Laravel\Cache\Drivers;class File extends Driver {/*** The path to which the cache ...

最新文章

  1. JSF实现“Hello World!”
  2. 小米手环无法模拟门卡_MIUI12轻体验:关于模拟门禁卡,你想知道的都在这里
  3. 去掉Phoca Download的Powered By
  4. shell 使用eval重新计算变量的变量
  5. hiho1015(kmp+统计出现次数)
  6. [转]有关TinyXML使用的简单总结
  7. java计算机毕业设计实验室耗材管理系统源码+系统+数据库+lw文档+mybatis+运行部署
  8. 主角把异能开发计算机,高等数学上下
  9. 哈尔滨工业大学车万翔:自然语言处理新范式
  10. pdf如何转化成word文档?
  11. win10使用软件提示“为了对电脑进行保护,已经阻止此应用”或软件上面有盾牌不能正常打开软件。
  12. html embed函数爬取,HTML DOM Embed用法及代码示例
  13. 纽约州立大学环境与林业学院计算机科学专业,2020年纽约州立大学环境科学与林业科学学院专业设置...
  14. 华为芯片鸿蒙的由来,华为“鸿蒙”真的来了!看完这些商标来历,网友们又激动了...
  15. 泊松融合(Poisson blend)
  16. XML是什么?有什么用?
  17. 2022/1/22 北京 mysql 多表关联查询,等值连接、非等值连接,外连接,内连接、自连接
  18. 芯片架构RISC-V、X86、ARM三足鼎立
  19. 手机怎么解决同ip多账号_问道手游:2019搬砖技巧分享,多开养号才是王道,三天肝出月卡...
  20. mysql实习报告总结_MYSQL实训心得

热门文章

  1. 软件工程师不可不知的10个概念
  2. 中修改环境变量_嵌入式 Linux下永久生效环境变量bashrc
  3. Java获取相同字符串算法题,数据结构与算法专题——第四题 字符串相似度
  4. linux docker安装mysql_Linux-docker安装mysql
  5. cpld xilinx 定义全局时钟_AutoSAR中的时钟同步机制
  6. 如何使用OpenCppCoverage检查单元测试的行覆盖率
  7. 在Windows下使用make命令
  8. ROS中RVIS导入机器人模型,添加摄像头,雷达,Kinect
  9. 【Interfacenavigation】选择时间/日期组件(34)
  10. phpcurl 请求Chunked-Encoded data 遇到的一个问题