在PetShop4.0的ReadMe.html中有如下配置步骤:
Asynchronous Order Placement Setup Instructions
1. Add a new private queue for Pet Shop called “PSOrders”
2. Modifyweb.config:
a. Change theOrderStrategyClass key to OrderAsynchronous
<add key="OrderStrategyClass" value="PetShop.BLL.OrderAsynchronous"/>
b. Change theMachineName in the following line to your MSMQ computer name.
<add key="OrderQueuePath" value="FormatName:DIRECT=OS:MachineName\Private$\PSOrders"/>
3. Modifyapp.config in the OrderProcessor project:
a. Change theMachineName in the OrderQueuePath key:
<add key="OrderQueuePath" value="FormatName:DIRECT=OS:MachineName\Private$\PSOrders"/>
注意:
1、第1步,建立一个新的专用队列“PSOrders”,队列是“事务性”的。建立时,要勾选“事务性”,如图示:
2、为数据库添加登录名mspetshop,密码为pass@word1,并设置服务器角色为sysadmin。当然你也可以修改app.config中的连接字符串中的用户名和密码。
1、先安装Message Queuing Services
通过Control Panel,“Add/Remove Programs” – “Add/Remove Windows Components”步骤安装MSMQ。
MSMQ可以安装为工作组模式或域模式。如果安装程序没有找到一台运行提供目录服务的消息队列的服务器,则只可以安装为工作组模式,此计算机上的“消息队列”只支持创建专用队列和创建与其他运行“消息队列”的计算机的直接连接。
2、配置MSMQ
打开Computer Management – Message Queuing,在Private Queues下创建MSMQDemo队列
3、编写代码-简单演示MSMQ对象
注意:
添加引用:System.Messaging
代码页:
// Send Message protected void btnSendMessage_Click(object sender, System.EventArgs e) { // Open queue System.Messaging.MessageQueue queue = new System.Messaging.MessageQueue(".\\Private$\\MSMQDemo"); // Create message System.Messaging.Message message = new System.Messaging.Message(); message.Body = txtMessage.Text.Trim(); message.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(string) }); // Put message into queue queue.Send(message); } // Receive Message protected void btnReceiveMessage_Click(object sender, System.EventArgs e) { // Open queue System.Messaging.MessageQueue queue = new System.Messaging.MessageQueue(".\\Private$\\MSMQDemo"); // Receive message, 同步的Receive方法阻塞当前执行线程,直到一个message可以得到 System.Messaging.Message message = queue.Receive(); message.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(string) }); txtReceiveMessage.Text = message.Body.ToString(); }
页面布局:
<table> <tr> <td style="width: 100px"> <asp:TextBox ID="txtMessage" runat="server"></asp:TextBox></td> <td style="width: 76px"> <asp:Button ID="btnSendMessage" runat="server" OnClick="btnSendMessage_Click" Text="Send Message" Width="132px" /></td> </tr> <tr> <td style="width: 100px"> <asp:TextBox ID="txtReceiveMessage" runat="server"></asp:TextBox></td> <td style="width: 76px"> <asp:Button ID="btnReceiveMessage" runat="server" OnClick="btnReceiveMessage_Click" Text="Receive Message" Width="130px" /></td> </tr> </table>