網頁

2011年8月29日 星期一

MSMQ Sample

Last Update: 2011/09/22 12:40+08


Intro

MSMQ Sampe!!
Listen 方法2種
1. Receive - 接到就刪
2. Peek - 接了不刪
這邊就只寫Receive的
遠端測試是可行的~

咱只用私用佇列(Private$)
公用佇列(Public$)需要在有AD的環境

下面會提到
1. Message Queue
2. 交易式 Message Queue


Content

1. Message Queue
接收方法/接收完成的事件
包含了重複的 Listen
private void btnReceive_Click(object sender, EventArgs e){
    var mqPath = @".\Private$\MqTest";
    if (!System.Messaging.MessageQueue.Exists(mqPath))
    { System.Messaging.MessageQueue.Create(mqPath); }

    var msgQueue = new System.Messaging.MessageQueue(mqPath);
    msgQueue.ReceiveCompleted += new System.Messaging.ReceiveCompletedEventHandler(msgQueue_ReceiveCompleted);
    msgQueue.BeginReceive();
}
void msgQueue_ReceiveCompleted(object sender, System.Messaging.ReceiveCompletedEventArgs e){
    var msgQueue = sender as System.Messaging.MessageQueue;
    var msg = msgQueue.EndReceive(e.AsyncResult);//suspend and get message
    msg.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(string) });
    LogRecorder.Log(msg.Label + "\n" + msg.Body);//Display
    msgQueue.BeginReceive();//Repeat Listen
}

Send方法~
private void btnSend_Click(object sender, EventArgs e){
    var mqPath = @"FormatName:Direct=TCP:192.168.1.30\Private$\MqTest";
    //var mqPath = @".\Private$\MqTest";//if local test
    var msgQueue = new System.Messaging.MessageQueue(mqPath);
    msgQueue.Send("Message Content", "Message Label");
}
就醬!!


2. 交易式(Transaction) Message Queue
要在創建 Message Queue 註明為交易式的Queue, 如下
System.Messaging.MessageQueue.Create(mqPath, true);
手動建立的話, 請至
控制台/系統及安全性/系統管理工具/電腦管理
=> 系統工具/服務與應用程式/訊息佇列/私用佇列
=> 右鍵 新增
=> 勾選 "交易式"


Receive 方法一樣
這邊講一下 Send 方法
private void btnTranSend_Click(object sender, EventArgs e){
    var mqPath = @".\Private$\MqTranTest";
    var msgQueue = new System.Messaging.MessageQueue(mqPath);
    var mqTran = new System.Messaging.MessageQueueTransaction();
    mqTran.Begin();
    msgQueue.Send("non-transaction body", "non-transaction label");//沒有transaction的不會被同意
    msgQueue.Send("transaction body", "transaction label", mqTran);
    mqTran.Commit();

    //可做一次性交易, 自動beginl, commit
    msgQueue.Send("single transaction body", "single transaction label", System.Messaging.MessageQueueTransactionType.Single);
}

End~

Reference

公用佇列需要 工作電腦在AD環境中
http://technet.microsoft.com/zh-tw/library/cc776346(WS.10).aspx

沒有留言:

張貼留言