二、事務性消息處理
事務我想大家對這個詞應該都不會陌生,在操作數據庫的時候經常都會用到事務,確保操作成功,要么全部完成(成功)
,要么全部不完成(失敗)。在MSMQ中利用事務性處理,可以確保事務中的消息按照順序傳送,只傳送一次,並且從目的隊列成
功地被檢索。
那么,在MSMQ上使用事務性處理怎么實現呢?可以通過創建MessageQueueTransation類的實例並將其關聯到MessageQueue
組件的實例來執行,執行事務的Begin方法,並將其實例傳遞到收發方法。然后,調用Commit以將事務的更改保存到目的隊列。
創建事務性消息和普通的消息有一點小小的區別,大家可從下圖上體會到:
1//創建普通的專用消息隊列
2MessageQueue myMessage = MessageQueue.Create(@".\private$\myQueue");
3//創建事務性的專用消息隊列
4MessageQueue myTranMessage =MessageQueue.Create(@".\private$\myQueueTrans", true);
啟動了事務,那么在發送和接收消息的時候肯定是與原來有一定的差別的,這里我就不做詳細介紹,下面給出示意性代碼,有興
趣的朋友可以直接下載本文示例程序代碼了解更多。
普通的消息發送示意性代碼:
1//連接到本地的隊列
2MessageQueue myQueue = new MessageQueue(".\\private$\\myQueue");
3Message myMessage = new Message();
4myMessage.Body = "消息內容";
5myMessage.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
6//發送消息到隊列中
7myQueue.Send(myMessage);
啟動了事務后的消息發送示意性代碼:
1//連接到本地的隊列
2MessageQueue myQueue = new MessageQueue(".\\private$\\myQueueTrans");
4Message myMessage = new Message();
5myMessage.Body = "消息內容";
6myMessage.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
8MessageQueueTransaction myTransaction = new MessageQueueTransaction();
9//啟動事務
10myTransaction.Begin();
11//發送消息到隊列中
12myQueue.Send(myMessage, myTransaction); //加了事務
13//提交事務
14myTransaction.Commit();
15Console.WriteLine("消息發送成功!");
讀取消息示意性代碼:
1//連接到本地隊列
2MessageQueue myQueue = new MessageQueue(".\\private$\\myQueueTrans");
3myQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
4if (myQueue.Transactional)
5{
MessageQueueTransaction myTransaction = new MessageQueueTransaction();
//啟動事務
myTransaction.Begin();
//從隊列中接收消息
Message myMessage = myQueue.Receive(myTransaction);
string context = myMessage.Body as string; //獲取消息的內容
myTransaction.Commit();
Console.WriteLine("消息內容為:" + context);
14}