想提升站点的性能,于是增加了缓存,但是站点不会太大,于是不会到分布式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. EntityFramework 学习 一 Lazy Loading 1

    延迟加载:延迟加载相关的数据 using (var ctx = new SchoolDBEntities()) { //Loading students only IList<Student&g ...

  2. 使用button的:after伪类选择器内容的跳动

    按钮的css样式,想要作个美观一点的按钮,使用:after伪类选择器在按钮后跟随"!!"的符号,但点击按钮时按钮的值内容动,但跟随的"!!"符合不动,这样看起来 ...

  3. HDU 2089 不要62:数位dp

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2089 题意: 问你在区间[n,m]中,有多少个数字不含"4"且不含"62 ...

  4. Web Worker浅学

    Web Workers 是 HTML5 提供的一个javascript多线程解决方案,我们可以将一些大计算量的代码交由web Worker运行而不冻结用户界面.它独立于其他脚本,不会影响页面的性能.您 ...

  5. MySQL常用方法

    1.INSTR,例:INSTR(content,'\"SHOP_DES\"')>0,返回字符串在某一个字段的内容中第一次出现位置,没有为0 2.REPLACE,例:conte ...

  6. Java微信开发_Exception_01_The type org.xmlpull.v1.XmlPullParser cannot be resolved. It is indirectly referenced from required .class files

    一.源码: package com.souvc.weixin.util; import java.io.InputStream; import java.io.Writer; import java. ...

  7. nodejs buffer 总结

    JavaScript 语言自身只有字符串数据类型,没有二进制数据类型.Buffer 类,该类用来创建一个专门存放二进制数据的缓存区. 一个 Buffer 类似于一个整数数组,但它对应于 V8 堆内存之 ...

  8. Convolutional Neural Networks for Visual Recognition 4

    Modeling one neuron 下面我们开始介绍神经网络,我们先从最简单的一个神经元的情况开始,一个简单的神经元包括输入,激励函数以及输出.如下图所示: 一个神经元类似一个线性分类器,如果激励 ...

  9. Maven发布项目丢失Mybatis Mapper包的映射问题

    由于一些eclipse版本问题,mybatis的mapper包中的sql文件没有被打进包,需要在pom中加入: <build> <!--配置打包时不过滤非java文件开始 --> ...

  10. FEC之我见一

    顾名思义,FEC前向纠错,根据收到的包进行计算获取丢掉的包,而和大神沟通的结果就是 纠错神髓:收到的媒体包+冗余包 >= 原始媒体包数据   直到满足 收到的媒体包+ 冗余包 >= 原始媒 ...