首页 技术 正文
技术 2022年11月15日
0 收藏 585 点赞 3,469 浏览 3087 个字

编写网络通讯都要面对一个问题,就是要把很久不存活的死连接清除,如果不这样做那死连接最终会占用大量内存影响服务运作!在实现过程中一般都会使用ping,pong原理,通过ping,pong来更新连接的时效性,最后通过扫描连接列表来清除掉。虽然这种做法比较简单,但很难抽取出通用性的封装,扫描整个列表复杂度也比较高。以下讲解如何通过LRU算法实现一个通用高效的探测超时连接功能类。

什么是LRU

在这里还是要大概介绍一下LRU,LRU算法的设计原则是:如果一个数据在最近一段时间没有被访问到,那么在将来它被访问的可能性也很小.也就是说,当限定的空间已存满数据时,应当把最久没有被访问到的数据淘汰.当然在这里并不需要使用到自动淘汰机制,只需要把未位到达超时的连接清除即可。

在C#中如何实现LRU

C#并不存在这样的数据结构,不过有一个结构很适合实现LRU,这个结构就是LinkedList双向链表,通过以下结构图就容易理解通过LinkedList实现LRU

通过LRU实现通用高效的超时连接探测

通过LinkedList的功能我们可以把活越项先移出来,然后再把项移到头部。在这里需要注意LinkedListRemove方法,它有两个重载版本,两个版本的复杂度不一样。一个是O(n)一个是O(1)所以使用上一定要注意,否则在数据多的情况下效率差别巨大(这些细节都可以通过源代码来查看)!

代码实现

前面已经大概讲述的原理,接下来要做的就是代码实现了。第一步需要制订一个基础可控测对象规则接口,这样就可以让现有的已经实现的功能实现它并可得到相关功能的支持。

    public interface IDetector
{
double ActiveTime
{ get; set; }
LinkedListNode<IDetector> DetectorNode
{
get;
set;
}
}

接口定义了两个属性,一个是最近活越时间,另一个就是LinkedListNode<IDetector>这个属性比交关键,通过LinkedListNode<IDetector>可以让LinkedListRemove时复杂度为O(1).接下来就要针对基于LRU算法处理超时制定一个应用规则

    public interface ILRUDetector
{
void Update(IDetector item); void Detection(int timeout); double GetTime(); Action<IList<IDetector>> Timeout { get; set; }
}

规则也是比较简单,Update用于更新跟踪对象,一般在处理接受ping或pong包后进行调用;Detection方法是探测超出指定时间的对象,时间当位是毫秒,如果存在有超时的对象则触发Timeout事件;GetTime是获取探测器已经运行的时间单位毫秒!规则定好了那接着要做的事实就是要实现它:

    class LRUDetector : ILRUDetector, IDisposable
{
public LRUDetector()
{
mTimeWatch = new System.Diagnostics.Stopwatch();
mTimeWatch.Restart();
}
private Buffers.XSpinLock xSpinLock = new Buffers.XSpinLock();
private System.Diagnostics.Stopwatch mTimeWatch;
private LinkedList<IDetector> mItems = new LinkedList<IDetector>();
public Action<IList<IDetector>> Timeout
{
get; set;
}
public void Detection(int timeout)
{
double time = GetTime();
List<IDetector> result = new List<IDetector>();
using (xSpinLock.Enter())
{
LinkedListNode<IDetector> last = mItems.Last;
while (last != null && (time - last.Value.ActiveTime) > timeout)
{
mItems.Remove(last);
result.Add(last.Value);
last.Value.DetectorNode = null;
last = mItems.Last;
}
}
if (Timeout != null && result.Count > )
Timeout(result);
}
public void Update(IDetector item)
{
using (xSpinLock.Enter())
{
if (item.DetectorNode == null)
item.DetectorNode = new LinkedListNode<IDetector>(item);
item.ActiveTime = GetTime();
if (item.DetectorNode.List == mItems)
mItems.Remove(item.DetectorNode);
mItems.AddFirst(item);
}
}
public void Dispose()
{
mItems.Clear();
}
public double GetTime()
{
return mTimeWatch.Elapsed.TotalMilliseconds;
}
}

代码并不复杂,相信不用过多解释也能看懂相关操作原理。

测试

既然功能已经实现,接下来就要对代码进行测试看运行效果。测试代码比较简单首先开启一个Timer定时执行Detection,另外开一个线程去调用Update方法

    class Program
{
public class TestDetector : IDetector
{
public double ActiveTime { get; set; }
public string Name { get; set; }
public LinkedListNode<IDetector> DetectorNode { get; set; }
}
static void Main(string[] args)
{
LRUDetector lRUDetector = new LRUDetector();
lRUDetector.Timeout = (items) =>
{
foreach (TestDetector item in items)
Console.WriteLine($"{(item.Name)} timeout {lRUDetector.GetTime() - item.ActiveTime}ms");
};
System.Threading.Timer timer = null;
timer = new System.Threading.Timer(o =>
{
timer.Change(-, -);
lRUDetector.Detection();
timer.Change(, );
}, null, , );
System.Threading.ThreadPool.QueueUserWorkItem(o =>
{
int i = ;
while (true)
{
System.Threading.Thread.Sleep();
i++;
TestDetector testDetector = new TestDetector();
testDetector.Name = "my name is " + i;
lRUDetector.Update(testDetector);
}
});
Console.Read();
}
}

运行效果:

通过LRU实现通用高效的超时连接探测

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,944
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,470
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,284
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,100
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,730
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,766