c# LRU实现的缓存类
在网上找到网友中的方法,将其修改整理后,实现了缓存量控制以及时间控制,如果开启缓存时间控制,会降低效率。
定义枚举,移除时使用
public enum RemoveType
{
[Description("超时移除")]
TimeOut,
[Description("超量移除")]
Capacity
}
定义委托,移除时使用
public delegate void RemoveKV<Tkey, TValue>(string cacheName, RemoveEntity<Tkey, TValue> entity);
定义缓存类
public class LRUCache<TKey, TValue>
{
const int DEFAULT_CAPACITY = int.MaxValue;
private int _capacity;
private ReaderWriterLockSlim locker;
private IDictionary<TKey, TValue> dictionary;//数据
private LinkedList<TKey> linkedList;//控制Key的数据
private Dictionary<TKey, LinkedListNode<TKey>> dicLinkIndex = null;//控制删除
private Dictionary<TKey, long> dicRefresh = null;//使用时间
private volatile bool isCheckTime = false;//设置是否监测缓存的时间长度
private long cacheTime = 600;//10分钟
private volatile bool isCheckThread = false;//检查线程启动
private long checkTicks = 0;//换算后的时间
private BlockingCollection<RemoveEntity<TKey, TValue>> removeEntities = null;
public event RemoveKV<TKey, TValue> RemoveEntitiesEvent = null;//移除通知
private DateTime checkTime = DateTime.Now;//结束监测的时间
/// <summary>
/// 设置缓存的时间长度,当前按照秒算
/// 设置时间自动设置属性IsCacheCheckTime=true
/// </summary>
public long CacheTime { get { return cacheTime; } set { cacheTime = value;isCheckTime = true; countTime(); } }
/// <summary>
/// 是否监测时间
/// </summary>
public bool IsCacheCheckTime { get { return isCheckTime; } set { isCheckTime = value; countTime(); } }
/// <summary>
/// cache名称
/// </summary>
public string CacheName { get; set; }
public LRUCache() : this(DEFAULT_CAPACITY) { }
public LRUCache(int capacity)
{
locker = new ReaderWriterLockSlim();
_capacity = capacity > 0 ? capacity : DEFAULT_CAPACITY;
dictionary = new Dictionary<TKey, TValue>();
linkedList = new LinkedList<TKey>();
dicLinkIndex = new Dictionary<TKey, LinkedListNode<TKey>>();
dicRefresh = new Dictionary<TKey, long>();
removeEntities = new BlockingCollection<RemoveEntity<TKey, TValue>>(1000);
countTime();
RemoveNotice();
}
/// <summary>
/// 换算时间;
/// 将秒转换成ticks个数
/// </summary>
private void countTime()
{
checkTicks = 10000000 * cacheTime;
}
/// <summary>
/// 更新时间
/// </summary>
/// <param name="key"></param>
private void Refresh(TKey key)
{
dicRefresh[key] = DateTime.Now.Ticks;
if(!isCheckTime)
{
return;
}
if(!isCheckThread)
{
isCheckThread = true;
Task.Factory.StartNew(() =>
{
double wait = (DateTime.Now - checkTime).TotalSeconds;
if(wait<cacheTime)
{
//如果上次监测到本次监测还未到设置的保持时间,
//则等待该时间差后再检查
double sleep = ((double)cacheTime-wait) * 1000+1;
Thread.Sleep((int)sleep);
}
locker.EnterWriteLock();
try
{
LinkedListNode<TKey> last = null;
long tick;
long curTick = DateTime.Now.Ticks;
last = linkedList.Last;//重后往前找
while (last != null)
{
if (dicRefresh.TryGetValue(last.Value, out tick))
{
if ((curTick - tick) > checkTicks)
{
dicLinkIndex.Remove(last.Value);
dicRefresh.Remove(last.Value);
linkedList.RemoveLast();
RemoveEntity<TKey, TValue> entity = new RemoveEntity<TKey, TValue>() { Key = last.Value, Value = dictionary[last.Value], RemoveType= RemoveType.TimeOut };
removeEntities.Add(entity);
dictionary.Remove(last.Value);
}
else
{
break;
}
}
last = linkedList.Last;
}
}
finally { locker.ExitWriteLock(); }
isCheckThread = false;
checkTime = DateTime.Now;
});
}
}
private void RemoveNotice()
{
Task.Factory.StartNew(() =>
{
while(true)
{
RemoveEntity<TKey, TValue> item=null;
if(removeEntities.TryTake(out item,500))
{
if(this.RemoveEntitiesEvent != null)
{
RemoveEntitiesEvent(CacheName, item);
}
}
}
});
}
public void Set(TKey key, TValue value)
{
locker.EnterWriteLock();
try
{
dictionary[key] = value;
LinkedListNode<TKey> item = null;
if(dicLinkIndex.TryGetValue(key,out item))
{
linkedList.Remove(item);
}
dicLinkIndex[key]= linkedList.AddFirst(key);
if (linkedList.Count > _capacity)
{
dictionary.Remove(linkedList.Last.Value);
dicLinkIndex.Remove(linkedList.Last.Value);
linkedList.RemoveLast();
dicRefresh.Remove(linkedList.Last.Value);
RemoveEntity<TKey, TValue> entity = new RemoveEntity<TKey, TValue>() { Key = linkedList.Last.Value, Value = dictionary[linkedList.Last.Value], RemoveType = RemoveType.Capacity };
removeEntities.Add(entity);
dictionary.Remove(linkedList.Last.Value);
}
Refresh(key);
}
finally { locker.ExitWriteLock(); }
}
public bool TryGet(TKey key, out TValue value)
{
locker.EnterUpgradeableReadLock();
try
{
bool b = dictionary.TryGetValue(key, out value);
if (b)
{
locker.EnterWriteLock();
try
{
linkedList.Remove(key);
linkedList.AddFirst(key);
}
finally { locker.ExitWriteLock(); }
}
Refresh(key);
return b;
}
catch { throw; }
finally { locker.ExitUpgradeableReadLock(); }
}
public void Clear()
{
locker.EnterWriteLock();
try
{
dictionary.Clear();
linkedList.Clear();
dicRefresh.Clear();
dicLinkIndex.Clear();
dicRefresh.Clear();
}
finally
{
locker.ExitWriteLock();
}
}
public bool Remove(TKey key)
{
bool isSucess = false;
locker.EnterWriteLock();
try
{
isSucess = dictionary.Remove(key);
dicRefresh.Remove(key);
LinkedListNode<TKey> item = null;
if (dicLinkIndex.TryGetValue(key, out item))
{
linkedList.Remove(item);
}
}
finally
{
locker.ExitWriteLock();
}
return isSucess;
}
public bool ContainsKey(TKey key)
{
locker.EnterReadLock();
try
{
return dictionary.ContainsKey(key);
}
finally { locker.ExitReadLock(); }
}
public int Count
{
get
{
locker.EnterReadLock();
try
{
return dictionary.Count;
}
finally { locker.ExitReadLock(); }
}
}
public int Capacity
{
get
{
locker.EnterReadLock();
try
{
return _capacity;
}
finally { locker.ExitReadLock(); }
}
set
{
locker.EnterUpgradeableReadLock();
try
{
if (value > 0 && _capacity != value)
{
locker.EnterWriteLock();
try
{
_capacity = value;
while (linkedList.Count > _capacity)
{
linkedList.RemoveLast();
}
}
finally { locker.ExitWriteLock(); }
}
}
finally { locker.ExitUpgradeableReadLock(); }
}
}
public ICollection<TKey> Keys
{
get
{
locker.EnterReadLock();
try
{
return dictionary.Keys;
}
finally { locker.ExitReadLock(); }
}
}
public ICollection<TValue> Values
{
get
{
locker.EnterReadLock();
try
{
return dictionary.Values;
}
finally { locker.ExitReadLock(); }
}
}
}
//最后在定一个异常的实体
public class RemoveEntity<TKey,TValue>
{
public TKey Key { get; set; }
public TValue Value { get; set; }
public RemoveType RemoveType { get; set; }
}
就完成了,测试代码
LRUCache<int, int> cache = new LRUCache<int, int>();
cache.RemoveEntitiesEvent += Cache_RemoveEntitiesEvent;
cache.CacheTime =3;//启动缓存时间
Random random = new Random();
DateTime start= DateTime.Now;
for(int i=0;i<10000000;i++)
{
cache.Set(i,random.Next());
}
Console.WriteLine("时间:" + (DateTime.Now - start).TotalSeconds);
Console.Read();
总共10-12秒;如果屏蔽缓存时间设置,7秒
代码已经传到GIT,地址和上一篇缓存模板一直,整合在同一个项目中。
c# LRU实现的缓存类的更多相关文章
- LinkedList实现基于LRU算法的缓存
LinkedList实现基于LRU算法的缓存 2015年08月07日 18:18:45 秦江波 阅读数 2068 文章标签: java算法linkedlist缓存LRU更多 分类专栏: Java ...
- ASP.NET Core 折腾笔记二:自己写个完整的Cache缓存类来支持.NET Core
背景: 1:.NET Core 已经没System.Web,也木有了HttpRuntime.Cache,因此,该空间下Cache也木有了. 2:.NET Core 有新的Memory Cache提供, ...
- 分享个 之前写好的 android 文件流缓存类,专门处理 ArrayList、bean。
转载麻烦声明出处:http://www.cnblogs.com/linguanh/ 目录: 1,前序 2,作用 3,特点 4,代码 1,前序 在开发过程中,client 和 server 数据交流一 ...
- cache4j轻量级java内存缓存框架,实现FIFO、LRU、TwoQueues缓存模型
简介 cache4j是一款轻量级java内存缓存框架,实现FIFO.LRU.TwoQueues缓存模型,使用非常方便. cache4j为java开发者提供一种更加轻便的内存缓存方案,杀鸡焉用EhCac ...
- (实用篇)PHP缓存类完整实例
本文完整描述了一个简洁实用的PHP缓存类,可用来检查缓存文件是否在设置更新时间之内.清除缓存文件.根据当前动态文件生成缓存文件名.连续创建目录.缓存文件输出静态等功能.对于采用PHP开发CMS系统来说 ...
- php简单缓存类
<?phpclass Cache { private $cache_path;//path for the cache private $cache_expire;//seconds ...
- ASP缓存类收集
木鸟写的 '********************************************** ' vbs Cache类 ' ' 属性valid,是否可用,取值前判断 ' 属性name,ca ...
- php简单数据缓存类
公司手机触屏站 ,由于页面图片太多,所以需要做数据缓存,就随便写一个数据缓存类. 直接贴代码 <?php/**** fianl_m@foxmail.com* 缓存类* 把数据查询出,并序列化写入 ...
- iOS缓存类的设计
使用执行速度缓存的程序可以大大提高程序,设计一个简单的缓存类并不需要太复杂的逻辑. 只需要一个简单的3接口. 存款对象 以一个对象 删除对象 阅读对象 watermark/2/text/aHR0cDo ...
随机推荐
- 在 Azure 中创建静态 HTML Web 应用
Azure Web 应用提供高度可缩放.自修补的 Web 托管服务. 本快速入门教程演示如何将基本 HTML+CSS 站点部署到 Azure Web 应用. 使用 Azure CLI 创建 Web 应 ...
- jquery解析xml
更多的项目都是在解析json,今天临时让解析几个xml文件,其实都一样,总结一下吧. 例如我们有这样一个xml文件 <?xml version="1.0" encoding= ...
- 自己用到的vim常用命令
一.前言 这里整理的是我在实习期间用到的常用vim命令,特记录如下,以免忘记. 二.vim常用命令 1.vim中的光标移动 shift+6(^):跳到行首(第一个非空格字符)(注:在shell跳到行首 ...
- PAT 1040 Longest Symmetric String
#include <cstdio> #include <cstdlib> using namespace std; ]; ]; int syslen(char str[], i ...
- css中的单位和css中的颜色表示方法
css中颜色的表示方式: 图片来源http://www.w3school.com.cn
- JQuery和html+css实现鼠标点击放烟花
<!DOCTYPE html> <html> <head><meta http-equiv="Content-Type" content= ...
- CSS中font-family:中文字体对应的英文名称
中文字体 对应英文字体 宋体 SimSun 黑体 SimHei 微软雅黑 Microsoft YaHei 微软正黑体 Microsoft JhengHei 新宋体 NSimSun 新细明体 PMing ...
- Android 从 Web 唤起 APP
前言 知乎在手机浏览器打开,会有个 App 内打开的按钮,点击直接打开且跳转到该详情页,是不是有点神奇,是如何做到的呢? 效果预览 Uri Scheme 配置 intent-filter Androi ...
- select * from pet where species regexp '^c';
select * from pet where species regexp '^c';
- CentOS 7 使用 yum 安装 jdk 1.8
安装之前先检查一下系统有没有自带open-jdk 命令: rpm -qa |grep java rpm -qa |grep jdk rpm -qa |grep gcj 如果没有输入信息表示没有安装. ...