首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

WCF 整合 MSMQ 訊息佇列:離線傳遞、持久化與重試機制完整指南

     編輯:關於.NET

WCF netMsmqBinding 提供企業級訊息佇列整合,支援離線傳遞、持久化儲存、重試機制與死信佇列處理,適合高可靠性非同步處理場景。

netMsmqBinding 關鍵屬性

屬性說明預設值
ExactlyOnce確保訊息僅投遞一次,需交易型佇列true
Durable訊息持久化,MSMQ 重啟不遺失enabled
TimeToLive訊息過期移至死信佇列時間1 天
ReceiveRetryCount重試佇列前嘗試投遞次數5
MaxRetryCycles最大重試週期數2
RetryCycleDelay重試週期間隔30 分鐘
ReceiveErrorHandling錯誤訊息處理:Fault/Drop/Reject/MoveFault
DeadLetterQueue死信佇列類型:None/System/CustomSystem

服務端實作

服務契約:單向操作

[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();
}

App.config 設定

<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。

運作特性驗證

  1. 啟動客戶端發送訊息(服務端未啟動)
  2. 訊息進入本機私有佇列 .\private$\SampleMSMQ
  3. 啟動服務端,自動從佇列讀取並處理所有待處理訊息
  4. 查看 C:\WCF_Log_MSMQ.txt 確認寫入結果

進階情境

  • 交易支援:服務操作加上 [OperationBehavior(TransactionScopeRequired = true)],失敗時訊息回滾重試
  • 死信佇列:過期或無法投遞訊息自動移至系統或自訂死信佇列
  • 毒藥訊息處理:ReceiveErrorHandling="Move" 將重試失敗訊息移至子佇列,避免阻塞主佇列

WCF + MSMQ 讓分散式系統獲得「至少一次」甚至「精確一次」的傳遞保證,是建構高可靠非同步架構的利器。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved