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

WCF 可靠傳訊:WS-ReliableMessaging 重試與有序傳遞實作

     編輯:關於.NET

WCF wsHttpBinding 內建支援 WS-ReliableMessaging 協定,透過 reliableSession 設定啟用訊息重試、重複偵測與有序傳遞,確保不可靠網路下的訊息完整送達。

核心機制

  • 重試機制:預設最多重試 8 次,網路中斷自動重送
  • 有序傳遞:ordered="true" 時,服務端緩衝區依客戶端呼叫順序排序處理
  • 工作階段:建立可靠會話,追蹤訊息序號與狀態

服務端實作

契約:要求有序傳遞

[ServiceContract]
[DeliveryRequirements(RequireOrderedDelivery = true)]
public interface IReliable {
    [OperationContract(IsOneWay = true)]
    void Write(string str);
}

實作:寫入記錄檔

public class Reliable : IReliable {
    public void Write(string str) {
        using (var sw = new StreamWriter(@"C:\WCF_Log_Reliable.txt", true)) {
            sw.WriteLine(str);
        }
    }
}

Web.config:啟用可靠會話

<bindings>
  <wsHttpBinding>
    <binding name="ReliableBindingConfiguration">
      <reliableSession enabled="true" ordered="true" inactivityTimeout="00:10:00" />
      <security mode="None" /> <!-- 示範用關閉安全性 -->
    </binding>
  </wsHttpBinding>
</bindings>

<services>
  <service name="WCF.ServiceLib.Message.Reliable" behaviorConfiguration="MessageBehavior">
    <endpoint address="https://localhost:8888/ServiceHost/Message/Reliable.svc"
        listenUri="https://localhost:3502/ServiceHost/Message/Reliable.svc"
        binding="wsHttpBinding" contract="WCF.ServiceLib.Message.IReliable"
        bindingConfiguration="ReliableBindingConfiguration" />
  </service>
</services>

listenUri 指定實際監聽位址,address 為客戶端連接位址(可搭配 TCP Trace 等工具攔截觀察)。

客戶端呼叫與測試

設定檔

<client>
  <endpoint address="https://localhost:8888/ServiceHost/Message/Reliable.svc"
      binding="wsHttpBinding" contract="MessageSvc.Reliable.IReliable"
      bindingConfiguration="ReliableBindingConfiguration" />
</client>

測試程式碼

using (var proxy = new MessageSvc.Reliable.ReliableClient()) {
    proxy.Write("1");
    Thread.Sleep(3000);
    proxy.Write("2");
}

驗證步驟

  1. 使用 TcpTrace 監聽 8888 連接埠,轉送至 3502
  2. 執行客戶端,呼叫 Write("1")
  3. 立即停止 TcpTrace(模擬網路中斷)
  4. 等待數秒後重新啟動 TcpTrace
  5. 觀察:Write("2") 仍會成功送達,且順序正確

進階設定說明

屬性說明
enabled啟用 WS-ReliableMessaging
ordered強制有序傳遞,需搭配 DeliveryRequirements(RequireOrderedDelivery=true)
inactivityTimeout非活動逾時關閉會話,預設 10 分鐘
maxRetryCount最大重試次數(進階設定,非直接屬性)

適用場景

  • 跨網域、不穩定網路環境的服務呼叫
  • 金融交易、訂單處理等不可遺失訊息場景
  • 需保證處理順序的工作流引擎

啟用可靠會話會增加通訊交握開銷,建議僅在必要時開啟,並搭配適當的 inactivityTimeout 避免閒置會話佔用資源。

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