WCF netMsmqBinding 提供企業級訊息佇列整合,支援離線傳遞、持久化儲存、重試機制與死信佇列處理,適合高可靠性非同步處理場景。
| 屬性 | 說明 | 預設值 |
|---|---|---|
| ExactlyOnce | 確保訊息僅投遞一次,需交易型佇列 | true |
| Durable | 訊息持久化,MSMQ 重啟不遺失 | enabled |
| TimeToLive | 訊息過期移至死信佇列時間 | 1 天 |
| ReceiveRetryCount | 重試佇列前嘗試投遞次數 | 5 |
| MaxRetryCycles | 最大重試週期數 | 2 |
| RetryCycleDelay | 重試週期間隔 | 30 分鐘 |
| ReceiveErrorHandling | 錯誤訊息處理:Fault/Drop/Reject/Move | Fault |
| DeadLetterQueue | 死信佇列類型:None/System/Custom | System |
[ServiceContract]
[DeliveryRequirements(QueuedDeliveryRequirements = QueuedDeliveryRequirementsMode.Required)]
public interface IMSMQ {
[OperationContract(IsOneWay = true)]
void Write(string str);
}
IsOneWay = true:MSMQ 必須為單向操作DeliveryRequirements:要求佇列傳遞public class MSMQ : IMSMQ {
public void Write(string str) {
using (var sw = new StreamWriter(@"C:\WCF_Log_MSMQ.txt", true)) {
sw.WriteLine(str);
}
}
}
string queueName = @".\private$\SampleMSMQ";
if (!MessageQueue.Exists(queueName)) {
MessageQueue.Create(queueName, true); // true = 交易型佇列
}
using (ServiceHost host = new ServiceHost(typeof(WCF.ServiceLib.Message.MSMQ))) {
host.Open();
Console.ReadLine();
}
<service name="WCF.ServiceLib.Message.MSMQ" behaviorConfiguration="MessageBehavior">
<endpoint address="" binding="netMsmqBinding" contract="WCF.ServiceLib.Message.IMSMQ" bindingConfiguration="MSMQBindingConfiguration" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="https://localhost:12345/Message/MSMQ" />
<add baseAddress="net.msmq://localhost/private/SampleMSMQ" />
</baseAddresses>
</host>
</service>
<netMsmqBinding>
<binding name="MSMQBindingConfiguration">
<security>
<transport msmqAuthenticationMode="None" msmqProtectionLevel="None" />
<message clientCredentialType="UserName" />
</security>
</binding>
</netMsmqBinding>
using (var proxy = new MessageSvc.MSMQ.MSMQClient()) {
proxy.Write("測試訊息 " + DateTime.Now);
}
客戶端 App.config 需對應相同的 netMsmqBinding 設定與端點位址 net.msmq://localhost/private/SampleMSMQ。
.\private$\SampleMSMQC:\WCF_Log_MSMQ.txt 確認寫入結果[OperationBehavior(TransactionScopeRequired = true)],失敗時訊息回滾重試ReceiveErrorHandling="Move" 將重試失敗訊息移至子佇列,避免阻塞主佇列WCF + MSMQ 讓分散式系統獲得「至少一次」甚至「精確一次」的傳遞保證,是建構高可靠非同步架構的利器。