[英]Processing MSMQ Message in Windows Service
我有一個用於處理MSMQ消息的Windows服務。 它依賴於以下邏輯
·Windows服務中有一個計時器。 每隔十分鍾,它將執行名為“ProcessMessages”的方法。
·在此方法中,它首先通過調用隊列的GetAllMessages方法創建現有messageIds的列表。
·對於每個messageId,它接收消息(使用ReceiveById)並將其存儲到文件中
有沒有更好的方法來實現消息處理?
參考: http : //www.switchonthecode.com/tutorials/creating-a-simple-windows-service-in-csharp
注意:當我將其作為服務時,以下代碼未提供所需的結果; 但是事件查看器中沒有錯誤(我沒有進行任何顯式記錄)。 當它是一個簡單的控制台應用程序時工作正常。 怎么糾正呢? [現在,當我在下面的評論中將會議改為“用戶”時,它正在工作]
我的行為要求是在固定的時間段處理所有消息 - 比如上午10點和上午11點(每天)。 這樣做的最佳方法是什么?
namespace ConsoleSwitchApp
{
class Program : ServiceBase
{
private static Timer scheduleTimer = null;
static MessageQueue helpRequestQueue = null;
static System.Messaging.XmlMessageFormatter stringFormatter = null;
static void Main(string[] args)
{
ServiceBase.Run(new Program());
}
public Program()
{
this.ServiceName = "LijosService6";
//Queue initialize
helpRequestQueue = new MessageQueue(@".\Private$\MyPrivateQueue", false);
stringFormatter = new System.Messaging.XmlMessageFormatter(new string[] { "System.String" });
//Set Message Filters
MessagePropertyFilter filter = new MessagePropertyFilter();
filter.ClearAll();
filter.Body = true;
filter.Label = true;
filter.Priority = true;
filter.Id = true;
helpRequestQueue.MessageReadPropertyFilter = filter;
//Start a timer
scheduleTimer = new Timer();
scheduleTimer.Enabled = true;
scheduleTimer.Interval = 120000;//2 mins
scheduleTimer.AutoReset = true;
scheduleTimer.Start();
scheduleTimer.Elapsed += new ElapsedEventHandler(scheduleTimer_Elapsed);
}
protected static void scheduleTimer_Elapsed(object sender, ElapsedEventArgs e)
{
ProcessMessages();
}
private static void ProcessMessages()
{
string messageString = "1";
//Message Processing
List<string> messageIdList = GetAllMessageId();
foreach (string messageId in messageIdList)
{
System.Messaging.Message messages = helpRequestQueue.ReceiveById(messageId);
//Store the message into database
messages.Formatter = stringFormatter;
string messageBody = System.Convert.ToString(messages.Body);
if (String.IsNullOrEmpty(messageString))
{
messageString = messageBody;
}
else
{
messageString = messageString + "___________" + messageBody;
}
}
//Write File
string lines = DateTime.Now.ToString();
lines = lines.Replace("/", "-");
lines = lines.Replace(":", "_");
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test" + lines + ".txt");
file.WriteLine(messageString);
file.Close();
}
private static List<string> GetAllMessageId()
{
List<string> messageIdList = new List<string>();
DataTable messageTable = new DataTable();
messageTable.Columns.Add("Label");
messageTable.Columns.Add("Body");
//Get All Messages
System.Messaging.Message[] messages = helpRequestQueue.GetAllMessages();
for (int index = 0; index < messages.Length; index++)
{
string messageId = (System.Convert.ToString(messages[index].Id));
messageIdList.Add(messageId);
messages[index].Formatter = stringFormatter;
messageTable.Rows.Add(new string[] { messages[index].Label, messages[index].Body.ToString() });
}
return messageIdList;
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
}
protected override void OnStop()
{
base.OnStop();
}
}
}
namespace ConsoleSwitchApp
{
[RunInstaller(true)]
public class MyWindowsServiceInstaller : Installer
{
public MyWindowsServiceInstaller()
{
var processInstaller = new ServiceProcessInstaller();
var serviceInstaller = new ServiceInstaller();
//set the privileges
processInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.DisplayName = "LijosService6";
serviceInstaller.StartType = ServiceStartMode.Manual;
//must be the same as what was set in Program's constructor
serviceInstaller.ServiceName = "LijosService6";
this.Installers.Add(processInstaller);
this.Installers.Add(serviceInstaller);
}
}
}
使用計時器的一個不錯的替代方法是使用MessageQueue.BeginReceive
方法並在ReceiveCompleted
事件中工作。 這樣,您的代碼將等待隊列中有消息,然后立即處理消息,然后檢查下一條消息。
短存根(鏈接的MSDN文章中的完整示例。)
private void Start()
{
MessageQueue myQueue = new MessageQueue(".\\myQueue");
myQueue.ReceiveCompleted +=
new ReceiveCompletedEventHandler(MyReceiveCompleted);
myQueue.BeginReceive();
}
private static void MyReceiveCompleted(Object source,
ReceiveCompletedEventArgs asyncResult)
{
try
{
MessageQueue mq = (MessageQueue)source;
Message m = mq.EndReceive(asyncResult.AsyncResult);
// TODO: Process the m message here
// Restart the asynchronous receive operation.
mq.BeginReceive();
}
catch(MessageQueueException)
{
// Handle sources of MessageQueueException.
}
return;
}
為什么不訂閱ReceiveCompleted事件? 另一個選擇,如果發件人和訂閱者都是您正在處理的.Net項目,則使用WCF而不是MSMQ 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.