缓存处理类(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> /// ...
随机推荐
- 句柄与MFC对象关系和相互获取
Windows对象是以句柄来标识的,对应的MFC类就是这些句柄的C++包装.内存中的Windows对象一定有唯一的句柄来标识,但不一定有对应的MFC类对象在内存中.当需要获取Windows对象的对应M ...
- JQUERY获取html标签自定义属性值或data值
//获取属性值 1 <div id="text" value="黑哒哒的盟友"><div> jQuery取值: $("#tex ...
- 京东自营,你TM太坑了。
双12来了,京东自营好坑.昨天(12月6日)看的一条秋裤,89元,今天准备买,居然涨到了119,他大爷的. 京东你大爷的.
- BAT系列(一)— CNN
1.CNN最成功的应用是在CV 那为什么NLP和Speech的很多问题也可以用CNN解出来?为什么AlphaGo里也用了CNN?这几个不相关的问题的相似性在哪里?CNN通过什么手段抓住了这个共性? 以 ...
- hdu-5867 Water problem(水题)
题目链接: Water problem Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Othe ...
- python中的排序函数
1.sort() list类型有一个自带的排序函数sort() list.sort(cmp=None, key=None, reverse=False) 参数说明: (1) cmp参数 cmp接受一 ...
- Eclipse或MyEclipse中给第三方jar包添加源码步骤
0.目的 向web项目中添加mybatis源码. 1.项目结构如下 将mybatis的jar包添加到工程中 2.解压下载的mybatis压缩包(下载地址 https://github.com/myba ...
- 服务注册选型比较:Consul vs Zookeeper vs Etcd vs Eureka
zookeeper基于paxos的化简版zab,etcd基于raft算法.consul也是基于raft算法.etcd和consul作为后起之秀,并没有因为已经有了zookeeper而放弃自己,而是采用 ...
- java多线程编程核心技术——第二章总结
第一节synchronized同步方法目录 1.1方法内的变量为线程安全的 1.2实例变量非线程安全 1.3多个对象多个锁 1.4synchronized方法与锁对象 1.5脏读 1.6synchro ...
- css中的特殊居中
大图居中: 先看一下普通的居中: 代码为: <!DOCTYPE html> <html lang="en"> <head> <meta c ...