MSMQ 事务性消息处理

二、事务性消息处理
事务我想大家对这个词应该都不会陌生,在操作数据库的时候经常都会用到事务,确保操作成功,要么全部完成(成功)
,要么全部不完成(失败)。在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}

posted @ 2017-11-02 17:23  任飞儿  阅读(1859)  评论(0编辑  收藏  举报