萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

.NET 訊息佇列 完整實作指南:安裝、建立、發送與接收訊息

前言:什麼是 MSMQ?

Microsoft Message Queuing (MSMQ) 是 Windows 內建的訊息佇列基礎設施,提供可靠的非同步通訊機制。應用程式可將訊息送入佇列,另一端程式稍後讀取處理,達成解耦、削峰填谷、跨程序/跨機器資料交換。本文涵蓋 Windows 7 安裝 MSMQ、程式碼建立佇列、發送/接收簡單與複雜物件訊息的完整範例。

一、Windows 7 安裝 MSMQ 元件

  1. 控制台 → 程式集 → 開啟或關閉 Windows 功能
  2. 勾選 Microsoft Message Queue (MSMQ) Server 及其子項目
  3. 確定安裝完成後,啟動「Message Queuing」服務 (services.msc)

MSMQ 安裝步驟 1 MSMQ 安裝步驟 2 MSMQ 安裝步驟 3 啟動 MSMQ 服務

二、核心程式碼實作 (C#)

專案需加入參考:System.Messaging

1. 定義訊息實體類別

[Serializable]
public class MsgModel
{
    public string Id { get; set; }
    public string Content { get; set; }

    public MsgModel(string id, string content)
    {
        Id = id;
        Content = content;
    }

    public override string ToString()
    {
        return $"Id:{Id}, Content:{Content}";
    }
}

2. 佇列操作封裝類別

using System;
using System.Messaging;

public class MsmqHelper
{
    private const string QueuePath = @".\private$\MsgQueue"; // 本機私有佇列

    // 確保佇列存在
    public static void EnsureQueueExists()
    {
        if (!MessageQueue.Exists(QueuePath))
        {
            MessageQueue.Create(QueuePath, true); // true = 交易型佇列
        }
    }

    // 發送簡單字串訊息
    public static void SendSimple(string label, string body)
    {
        EnsureQueueExists();
        using (var mq = new MessageQueue(QueuePath))
        {
            var msg = new Message
            {
                Label = label,
                Body = body,
                Formatter = new XmlMessageFormatter(new Type[] { typeof(string) })
            };
            mq.Send(msg);
        }
    }

    // 接收簡單字串訊息
    public static string ReceiveSimple()
    {
        EnsureQueueExists();
        using (var mq = new MessageQueue(QueuePath))
        {
            mq.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
            if (mq.GetAllMessages().Length > 0)
            {
                var msg = mq.Receive(TimeSpan.FromSeconds(5));
                return msg?.Body?.ToString();
            }
        }
        return null;
    }

    // 發送複雜物件 (需 Serializable)
    public static void SendComplex(string label, T body) where T : class
    {
        EnsureQueueExists();
        using (var mq = new MessageQueue(QueuePath))
        {
            var msg = new Message
            {
                Label = label,
                Body = body,
                Formatter = new XmlMessageFormatter(new Type[] { typeof(T) })
            };
            mq.Send(msg);
        }
    }

    // 接收複雜物件 (泛型)
    public static T ReceiveComplex() where T : class
    {
        EnsureQueueExists();
        using (var mq = new MessageQueue(QueuePath))
        {
            mq.Formatter = new XmlMessageFormatter(new Type[] { typeof(T) });
            if (mq.GetAllMessages().Length > 0)
            {
                var msg = mq.Receive(TimeSpan.FromSeconds(5));
                return msg?.Body as T;
            }
        }
        return null;
    }
}

3. 網頁測試頁面 MSMQtest.aspx.cs

public partial class MSMQtest : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // 測試發送與接收複雜物件
        MsmqHelper.SendComplex("ComplexMsg", new MsgModel("1", "測試訊息內容"));
        var model = MsmqHelper.ReceiveComplex();
        
        if (model != null)
            Response.Write($"接收成功: {model}
"); else Response.Write("佇列無訊息
"); } }

三、關鍵觀念與最佳實務

  • 佇列路徑格式:.\private$\QueueName (本機私有)、MachineName\private$\QueueName (遠端)。
  • Formatter 選擇:XmlMessageFormatter 跨平台相容性佳;BinaryMessageFormatter 效能較好但限 .NET 環境;ActiveXMessageFormatter 相容舊版 COM。
  • 交易型佇列:建立時指定 true 可支援分散式交易 (DTC),確保訊息處理的原子性。
  • 訊息屬性:Label 供人工識別,Priority 控制優先順序,Recoverable 確保斷電不遺失。
  • 錯誤處理:Receive 會封鎖執行緒,生產環境建議使用非同步 BeginReceive 或 Task.Run 配合 CancellationToken。

四、常見問題排查

現象可能原因解決方向
存取被拒佇列權限不足右鍵佇列 → 內容 → 安全性 → 加入 IIS_IUSRS / 網路服務 完整控制
序列化失敗型別未標記 Serializable類別加上 [Serializable] 或改用 DataContractSerializer
找不到佇列路徑拼寫錯誤或未建立啟動時呼叫 EnsureQueueExists() 自動建立

總結

MSMQ 是 Windows 平台上成熟可靠的訊息中介軟體,適合企業內部系統整合、背景作業排程、跨服務非同步通訊。掌握安裝配置、佇列建立、訊息序列化與收發流程,即可在 .NET 應用中輕鬆導入可靠的非同步訊息機制。

copyright © 萬盛學電腦網 all rights reserved