消息队列操作
消息队列主要是用来处理两台计算机或者两个应用程序之间的消息传递。
Receive接受完之后,就删除该Message。Peek接受完不删除该Message。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Messaging;
using System.Net;
using System.IO;
using System.Diagnostics;
namespace Egensource.MessageQueue.SMS
{
public class SMS
{
private const string smsUrl = System.Configuration.ConfigurationSettings.AppSettings["SMSUrl"].ToString();
/// <summary>
/// 发送消息队列,用来发送短信
/// </summary>
/// <param name="mqName">消息队列名称</param>
/// <param name="smsinfo">短信信息对象</param>
public void SendMessage(string mqName, SMSInfo smsinfo)
{
MessageQueue mq;
if (MessageQueue.Exists(@".\private$\" + mqName))
{
mq = new MessageQueue(@".\private$\" + mqName);
}
else
{
mq = MessageQueue.Create(@".\private$\" + mqName, true);
}
if (mq.Transactional)
{
MessageQueueTransaction myTransaction = new MessageQueueTransaction();
try
{
myTransaction.Begin();
mq.Send(string.Format(smsUrl, smsinfo.Mobile, smsinfo.Body, myTransaction));
myTransaction.Commit();
}
catch (Exception ex)
{
myTransaction.Abort();
WriteLog(ex.ToString());
}
}
}
/// <summary>
/// 发送短信
/// </summary>
/// <param name="mqName"></param>
public void SendSMS(string mqName)
{
MessageQueue mq;
string strResult = string.Empty;
if (MessageQueue.Exists(@".\private$\" + mqName))
{
mq = new MessageQueue(@".\private$\" + mqName);
if (mq.Transactional)
{
Message[] messages = mq.GetAllMessages();
foreach (Message message1 in messages)
{
MessageQueueTransaction myTransaction = new MessageQueueTransaction();
try
{
myTransaction.Begin();
System.Messaging.Message message = mq.Receive(myTransaction);
message.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
myTransaction.Commit();
}
catch (Exception ex)
{
myTransaction.Abort();
WriteLog("发送失败。返回值:" + ex.ToString() + "。");
}
}
}
}
}
#region Write System Log
public static void WriteLog(string ex)
{
if (!EventLog.SourceExists("MessageQueue"))
{
EventLog.CreateEventSource("MessageQueue", "MessageQueueLog");
}
EventLog.WriteEntry("MessageQueue", ex.ToString(), EventLogEntryType.Error);
}
#endregion
}
}