消息队列数量统计(MSMQ,Performance Counter)


微软消息队列服务MSMQ (Microsoft Message Queue),工作在在线或者离线场景,并提供异步编程功能。互联网和企业开发很多场景应用,例如电商的订单处理流程,这是因为客户端不需要等待服务端返回确认。

项目开发中用MSMQ分为公有队列(Public)和私有队列(Private),主要区别是接收,私有队列需要本地接收,或者调用WMI接收,公有队列远程接收需要有域用户权限。创建消息队列的时候分为事务和非事务,主要区别是非事务队列存储在内存,事务队列存储在内存和硬盘,重启Windows后非事务队列清空。事务队列发送和接收的性能要比非事务队列低50%左右,在一台服务器具体情况还要看消息的大小。

某些情况下需要统计消息消息数量,用来监控队列状态,如消息堆积数量过大时需要预警。统计消息有两种方式, Performance Counter(性能计数器)和WMI(Windows Management Instrumentation,Windows 管理规范),两者性能接近。如果只是消息数量统计,推荐用简单的Performance Counter。

 //MSMQ性能计数器
PerformanceCounterCategory countCategory = new PerformanceCounterCategory("MSMQ Queue");

//所有消息队列数量
PerformanceCounter allCount = new PerformanceCounter("MSMQ Queue", "Messages in Queue");
foreach (string instanceName in countCategory.GetInstanceNames())
{
    allCount.InstanceName = instanceName;//需要给实例名赋值
    Console.WriteLine(string.Format("{0} 数量:{1}", allCount.InstanceName, allCount.NextValue().ToString()));
}


//单个消息队列数量
PerformanceCounter singleCount = new PerformanceCounter("MSMQ Queue", "Messages in Queue", Environment.MachineName + "\private$\queue_demo");
singleCount.InstanceName = Environment.MachineName + "\private$\queue_demo";
Console.WriteLine(string.Format("{0} 数量:{1}", singleCount.InstanceName, singleCount.NextValue().ToString()));
原文地址:https://www.cnblogs.com/geekcoffee/p/3474241.html