缓存处理类(MemoryCache结合文件缓存)
想提升站点的性能,于是增加了缓存,但是站点不会太大,于是不会到分布式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结合文件缓存)的更多相关文章
- Cache【硬盘缓存工具类(包含内存缓存LruCache和磁盘缓存DiskLruCache)】
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 内存缓存LruCache和磁盘缓存DiskLruCache的封装类,主要用于图片缓存. 效果图 代码分析 内存缓存LruCache和 ...
- ASP.NET缓存全解析5:文件缓存依赖 转自网络原文作者李天平
这种策略让缓存依赖于一个指定的文件,通过改变文件的更新日期来清除缓存. ///<summary> /// 获取当前应用程序指定CacheKey的Cache对象值 ///</summa ...
- [Android]异步加载图片,内存缓存,文件缓存,imageview显示图片时增加淡入淡出动画
以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/3574131.html 这个可以实现ImageView异步加载 ...
- app缓存设计-文件缓存
采用缓存,可以进一步大大缓解数据交互的压力,又能提供一定的离线浏览.下边我简略列举一下缓存管理的适用环境: 1. 提供网络服务的应用 2. 数据更新不需要实时更新,哪怕是3-5分钟的延迟也是可以采用缓 ...
- php 文件缓存
http://www.oschina.net/code/snippet_162279_6098 <?php class cache { private static $_instan ...
- php文件缓存
1.最新代码 <?php class cache { private static $_instance = null; protected $_options = array( 'cache_ ...
- php 缓存工具类 实现网页缓存
php 缓存工具类 实现网页缓存 php程序在抵抗大流量访问的时候动态网站往往都是难以招架,所以要引入缓存机制,一般情况下有两种类型缓存 一.文件缓存 二.数据查询结果缓存,使用内存来实现高速缓存 本 ...
- thrift之TTransport层的缓存传输类TBufferedTransport和缓冲基类TBufferBase
本节主要介绍缓冲相关的传输类,缓存的作用就是为了提高读写的效率.Thrift在实现缓存传输的时候首先建立一个缓存的基类,然后需要实现缓存功能的类都可以直接从这个基类继承.下面就详细分析这个基类以及一个 ...
- [Cache] C#操作缓存--CacheHelper缓存帮助类 (转载)
点击下载 CacheHelper.zip CacheHelper 缓存帮助类 C#怎么操作缓存 怎么设置和取缓存数据,都在这个类里面呢 下面看一下代码吧 /// <summary> /// ...
随机推荐
- zookeeper 配置文件注释
tickTime=2000 initLimit=5 syncLimit=2 dataDir=/opt/shencl/zookeeper/data/data0 dataLogDir=/opt/shenc ...
- Java Applet:练习TextField类和TextArea类的文本事件
出自: Java语言与面向程序程序设计(第二版) 第七章第五节P223 1. [代码]java代码 /** *这个程序主要来练习文本事件,当在文本框(TextField)中输入文字时,会在文本域(Te ...
- GridView行中按钮的使用
转载自:http://blog.csdn.net/hongdi/article/details/6455947 GridView行中按钮的使用 在web项目的过程中,特别是开发ASP.NET应用程序, ...
- 泛型,注解,反射配合优化BaseDao的猜想
package test; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.la ...
- MicroMessage的动态操作(第二步)
现在开始将静态页面转化成动态页面.将页面上的信息转化成 数据库提供的信息. 建立jdbc获取数据库连接,并设置一个查询sql语句,查出所有结果.但是因为查询结果rs包含全表信息,是多行. 为了保存查询 ...
- 51nod1428 活动安排问题 (贪心加暴力)
1428 活动安排问题 基准时间限制:1 秒 空间限制:131072 KB 分值: 10 难度:2级算法题 收藏 关注 有若干个活动,第i个开始时间和结束时间是[Si,fi),同一个教室安排的活动 ...
- WampServer 2.5设置外网访问/局域网手机访问(403 Forbidden错误解决方法)
安装好wamp后,想用手机通过局域访问电脑上wamp下的网页,结果出现如下提示. (403 Forbidden)错误 1.打开http.conf文件 2.找到下图中红色方框中的onlineofflin ...
- linux绑定多个ip(转载)
在Linux下有时候需要给一个网卡绑定多个IP,本文介绍在Redhat系列(redhat,Fedora Core,Centos)中的实现方法和一种在Gentoo等其他Linux中普遍适用的方法. 1. ...
- HBase的bulkLoad
HBase的BulkLoad有两种方式: thinrow的机制是flatmap把cell的信息进行flatmap:适合少于1万列的数据集:thinrow的涵义就是少行多列: bulkload的机制则是 ...
- HDOJ(1069)最长下降子序列
每个箱子可有3种叠加方式,所以有3*n个箱子.将箱子按长度由大到小排序,有求箱子按宽度的最长下降子序列的高度之和即可. #include<cstdio> #include<algor ...