想提升站点的性能,于是增加了缓存,但是站点不会太大,于是不会到分布式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 == )
{
MemoryCache _cache = System.Runtime.Caching.MemoryCache.Default;
foreach (var _c in _cache.GetValues(null))
{
_cache.Remove(_c.Key);
}
}
else if (type == )
{
DirectoryInfo di = new DirectoryInfo(filePath);
di.Delete(true);
}
} #region 流序列化
public static void BinarySerialize(Stream stream, object obj)
{
try
{
stream.Seek(, 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(, 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
}
}

缓存处理类(MemoryCache结合文件缓存)的更多相关文章

  1. Cache【硬盘缓存工具类(包含内存缓存LruCache和磁盘缓存DiskLruCache)】

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 内存缓存LruCache和磁盘缓存DiskLruCache的封装类,主要用于图片缓存. 效果图 代码分析 内存缓存LruCache和 ...

  2. ASP.NET缓存全解析5:文件缓存依赖 转自网络原文作者李天平

    这种策略让缓存依赖于一个指定的文件,通过改变文件的更新日期来清除缓存. ///<summary> /// 获取当前应用程序指定CacheKey的Cache对象值 ///</summa ...

  3. [Android]异步加载图片,内存缓存,文件缓存,imageview显示图片时增加淡入淡出动画

    以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/3574131.html  这个可以实现ImageView异步加载 ...

  4. app缓存设计-文件缓存

    采用缓存,可以进一步大大缓解数据交互的压力,又能提供一定的离线浏览.下边我简略列举一下缓存管理的适用环境: 1. 提供网络服务的应用 2. 数据更新不需要实时更新,哪怕是3-5分钟的延迟也是可以采用缓 ...

  5. php 文件缓存

    http://www.oschina.net/code/snippet_162279_6098 <?php class cache {       private static $_instan ...

  6. php文件缓存

    1.最新代码 <?php class cache { private static $_instance = null; protected $_options = array( 'cache_ ...

  7. php 缓存工具类 实现网页缓存

    php 缓存工具类 实现网页缓存 php程序在抵抗大流量访问的时候动态网站往往都是难以招架,所以要引入缓存机制,一般情况下有两种类型缓存 一.文件缓存 二.数据查询结果缓存,使用内存来实现高速缓存 本 ...

  8. thrift之TTransport层的缓存传输类TBufferedTransport和缓冲基类TBufferBase

    本节主要介绍缓冲相关的传输类,缓存的作用就是为了提高读写的效率.Thrift在实现缓存传输的时候首先建立一个缓存的基类,然后需要实现缓存功能的类都可以直接从这个基类继承.下面就详细分析这个基类以及一个 ...

  9. [Cache] C#操作缓存--CacheHelper缓存帮助类 (转载)

    点击下载 CacheHelper.zip CacheHelper 缓存帮助类 C#怎么操作缓存 怎么设置和取缓存数据,都在这个类里面呢 下面看一下代码吧 /// <summary> /// ...

随机推荐

  1. SpringCloud-断路器(Hystrix)

    在微服务架构中,根据业务来拆分成一个个的服务,服务与服务之间可以相互调用(RPC),在Spring Cloud可以用Rest Template + Ribbon和Feign来调用.为了保证其高可用,单 ...

  2. Entity Framework 学习笔记(一)之数据模型 数据库

    关于Entity Framework  数据模型 的开发有三种模式:1.引用数据库方式:2.在VS中新建EF空模型Model 方式:3.Code 方式 Entity Framework  数据模型   ...

  3. C++(九)— 虚函数、纯虚函数、虚析构函数

    1.虚函数 原因:通过指针调用成员函数时,只能访问到基类的同名成员函数.在同名覆盖现象中,通过某个类的对象(指针及引用)调用同名函数,编译器会将该调用静态联编到该类的同名函数,也就是说,通过基类对象指 ...

  4. node Express安装和使用

    1:在cmd命令行下执行npm install -g express,安装全局的express 2:进入需要创建项目的目录下执行express nodeExpressProject,创建express ...

  5. 十九 Django框架,发送邮件

    全局配置settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' #发送邮件引擎 EMAIL_USE_TLS ...

  6. Selenium-使用firepath获取元素的xpath

  7. 宽度显示banner

    今天解决了一个以前解决不了的问题,所以就想找博客园记录一些笔记. ……以前也遇到过这种满屏banner不知道怎么做的问题,问老师老师也说不出个所以然,百度搜了好几条 也不太满意... 所以就开始尝试摸 ...

  8. 百度编辑器UEditor配置toolbars工具条功能按钮

    两种方式: 1.代码中定义 <script id="container" name="content" type="text/plain&quo ...

  9. C语言小程序(八)、统计字母个数

    这么简单的程序本不应贴在这里,但每写一篇博客,积分涨10分,距离摆脱千里之外的排名又进一步,相当于刷榜了,哈哈! #include <stdio.h> #include <strin ...

  10. AAC_LC用LATM封装header信息解析 Audio Specific Config格式分析

    通常来说AAC的头信息在编解码过程中是可以获取到的,但今天需要根据音频参数生成相应的AAC头.项目中使用的是AAC_LC,今天先对它的结构进行分析. 项目中使用ffmpeg进行音频编码,音频编码库为F ...