想提升站点的性能,于是增加了缓存,但是站点不会太大,于是不会到分布式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. Delphi 运行Word VBA 宏 删除软回车

    Sub 整理网页()'整理网页:删除软回车.删除空白段.使段落文字两端对齐Selection.WholeStory        Selection.Find.ClearFormatting    S ...

  2. for循环中删除map中的元素,valgrind检测提示error:Invalid read of size 8

    #include <iostream> #include <map> using namespace std; class A { public: typedef std::m ...

  3. phalcon:官方多模块支models层,mode数据库配置(二)

    phalcon:官方多模块支models层,mode数据库配置(二) 利用:\pahlcon\mvc\model\Manager::registerNamespaceAlias()方法获取多模块下的m ...

  4. HTML5 学习记录——2

    20150826 1.声明文档类型 <!DOCTYPE>  声明HTML是用什么版本写的. 常用声明; 2.HYML头部元素   <head> <title> 定义 ...

  5. DELPHI线程例子-FC

    {优秀的数据库应用应当充分考虑数据库访问的速度问题.通常可以通过优化数据库.优化 查询语句.分页查询等途径收到明显的效果.即使是这样,也不可避免地会在查询时闪现一个带有 SQL符号的沙漏,即鼠标变成了 ...

  6. 分享知识-快乐自己:java代码 操作 solr

    POM 文件: <!-- solr客户端 --> <dependency> <groupId>org.apache.solr</groupId> < ...

  7. 什么是 Sass 其与SCSS区别是什么?

    Sass 官网上是这样描述 Sass 的: Sass 是一门高于 CSS 的元语言,它能用来清晰地.结构化地描述文件样式,有着比普通 CSS 更加强大的功能. Sass 能够提供更简洁.更优雅的语法, ...

  8. Vue从接口请求数据

    <!doctype html> <html> <head> <meta charset="UTF-8"> <title> ...

  9. C/C++ 安全编码 —— 不安全的函数

    1. 文件与IO操作 gets():从控制台输入到字符数组: char response[8]; gets(response); 如果控制台输入超过 8 个字符,程序便会发生不确定的行为.其主要问题在 ...

  10. django models class 不识别问题解决方案

    目录 1. 事情起因 2. 排查经过 3. 总结 1. 事情起因 今天在写代码的时候,在django 的models目录中新增了一个pkg.py文件,里面定义了一个class, 在执行 makemig ...