共用方式為


快速入門:從 Azure 服務匯流排佇列傳送及接收訊息 (.NET)

在本快速入門中,您會執行下列步驟:

  1. 使用 Azure 入口網站建立服務匯流排命名空間。

  2. 使用 Azure 入口網站建立服務匯流排佇列。

  3. 撰寫 .NET 主控台應用程式,將一組訊息傳送到佇列。

  4. 撰寫 .NET 主控台應用程式,從佇列接收這些訊息。

    本快速入門提供逐步指示,以實作將一批訊息傳送至 服務匯流排 佇列,然後接收訊息的簡單案例。 如需 .NET 用戶端程式庫的概觀,請參閱適用於 .NET 的 Azure 服務匯流排用戶端程式庫。 如需更多樣本,請參閱 GitHub 上的服務匯流排 .NET 樣本

必要條件

如果您不熟悉服務,請先參閱服務匯流排概觀,再執行本快速入門。

  • Azure 訂用帳戶。 若要使用 Azure 服務 (包括 Azure 服務匯流排),您需要訂用帳戶。 如果您沒有現有 Azure 帳戶,您可以註冊免費試用
  • Visual Studio 2022。 範例應用程式會使用 C# 10 中引進的新功能。 您仍然可以搭配先前的 C# 語言版本使用服務匯流排用戶端程式庫,但語法可能會有所不同。 若要使用最新的語法,建議您安裝 .NET 6.0 或更高版本,並將語言版本設定為 latest。 如果您使用的是 Visual Studio,Visual Studio 2022 之前的版本與建置 C# 10 專案所需的工具不相容。

在 Azure 入口網站中建立命名空間

若要開始使用 Azure 中的服務總線傳訊實體,請建立命名空間,其名稱在 Azure 中是唯一的。 命名空間會為應用程式中的服務總線資源提供範圍容器,例如佇列和主題。

若要建立命名空間:

  1. 登入 Azure 入口網站

  2. 從左上方選取展開選單,然後導航至所有服務頁面

  3. 在左側導覽列上,選取 [整合]。

  4. 向下卷動至 [傳訊服務>服務總線 ],然後選取 [ 建立]。

    顯示選取 [建立資源]、[整合] 和功能表中 [服務總線] 的螢幕快照。

  5. 在 [建立命名空間] 頁面的 [基本] 索引標籤中,遵循下列步驟:

    1. 針對 [訂用帳戶],選擇要在其中建立命名空間的 Azure 訂用帳戶。

    2. 針對 [ 資源群組],選擇現有的資源群組,或建立新的資源群組。

    3. 輸入符合下列命名慣例的 命名空間名稱

      • 名稱在整個 Azure 中必須是唯一的。 系統會立即檢查此名稱是否可用。
      • 名稱長度至少 6 個字元,最多 50 個字元。
      • 名稱只能包含字母、數位、連字元 -
      • 名稱開頭必須為字母,且結尾必須為字母或數字。
      • 名稱結尾不是 -sb-mgmt
    4. 針對 位置,選擇用於部署命名空間的區域。

    5. 針對定價層,選取命名空間的定價層 (基本、標準或進階)。 針對本快速入門,選取 [標準]

      如果您選取 Premium 層,您可以啟用命名空間的 異地複寫。 異地復寫功能可確保命名空間的元數據和數據會持續從主要區域複寫到一或多個次要區域。

      重要

      如果您想要使用主題和訂用帳戶,請選擇 [標準] 或 [進階]。 基本定價層不支援主題和訂用帳戶。

      若已選取 [進階] 定價層,請指定傳訊單位數目。 進階層可讓您的資源在 CPU 和記憶體層級上獲得隔離,讓每個工作負載能夠獨立執行。 此資源容器稱為「傳訊單位」 。 進階命名空間都至少有一個傳訊單位。 您可以為每個服務匯流排的進階命名空間選取 1、2、4、8 或 16 個傳訊單位。 如需詳細資訊,請參閱 服務總線進階傳訊層

    6. 選取頁面底部的 [檢閱 + 建立] 。

      顯示 [建立命名空間] 頁面的螢幕快照

    7. 在 [檢閱 + 建立] 頁面上檢閱設定,然後選取 [建立]

  6. 部署資源成功之後,請選取部署頁面上的 [移至資源 ]。

    顯示部署成功頁面的螢幕快照,其中包含 [移至資源] 連結。

  7. 您會看到服務匯流排命名空間的首頁。

    顯示所建立服務總線命名空間首頁的螢幕快照。

在 Azure 入口網站中建立佇列

  1. [服務匯流排 命名空間] 頁面上,展開左側導覽功能表上的 [實體],然後選取 [佇列]。

  2. 佇列 頁面上的工具列中,選取 + 佇列

  3. 輸入佇列的名稱。 將其他值保留為預設值。

  4. 選取 ,創建

    顯示 [建立佇列] 頁面的螢幕快照。

重要

如果您不熟悉 Azure,您可能會發現 [連接字串 ] 選項更容易遵循。 選取 [連接字串] 索引標籤,以查看在本快速入門中使用連接字串的指示。 建議在真實世界應用程式和實際執行環境中使用 [無密碼] 選項。

向 Azure 驗證應用程式

本文說明連線到 Azure 服務總線的兩種方式: 無密碼連接字串

第一個選項顯示如何使用 Microsoft Entra ID 中的安全性主體和角色型存取控制 (RBAC),來連線到服務匯流排命名空間。 您不需要擔心在程式代碼、組態檔中或 Azure Key Vault 等安全記憶體中有硬式編碼連接字串。

第二個選項顯示如何使用連接字串來連線到服務匯流排命名空間。 如果您不熟悉 Azure,您可能會發現 連接字串 選項更容易遵循。 建議在真實世界應用程式和實際執行環境中使用無密碼選項。 如需詳細資訊,請參閱 服務總線驗證和授權。 若要深入瞭解無密碼驗證,請參閱 驗證 .NET 應用程式

將角色指派給 Microsoft Entra 使用者

當您在本機開發時,請確定連線到 Azure 服務總線的用戶帳戶具有正確的許可權。 您需要 Azure 服務總線數據擁有者 角色,才能傳送和接收訊息。 若要自我指派此角色,您需要使用者存取管理員角色,或包括 Microsoft.Authorization/roleAssignments/write 動作的另一個角色。

您可以使用 Azure 入口網站、Azure CLI 或 Azure PowerShell,將 Azure RBAC 角色指派給使用者。 若要深入瞭解角色指派的可用範圍,請參閱 瞭解 Azure RBAC 的範圍

下列範例會將 Azure Service Bus Data Owner 角色指派給您的使用者帳戶,該角色提供對 Azure 服務匯流排資源的完整存取權。 在實際案例中,遵循 最低許可權原則 ,只為使用者提供更安全的生產環境所需的最低許可權。

Azure 服務匯流排的 Azure 內建角色

對於 Azure 服務匯流排來說,透過 Azure 入口網站和 Azure 資源管理 API 來的管理命名空間和所有相關資源的作業,皆已使用 Azure RBAC 模型來加以保護。 Azure 提供下列 Azure 內建角色,以授權存取服務匯流排命名空間:

如果您想要建立自訂角色,請參閱服務匯流排作業所需的權限

將 Microsoft Entra 使用者新增至 Azure 服務匯流排擁有者角色

將您的 Microsoft Entra 使用者名稱新增至服務匯流排命名空間層級的 Azure 服務匯流排資料擁有者角色。 此設定可讓在使用者帳戶內容中執行的應用程式,將訊息傳送至佇列或主題。 此系統可以從佇列或主題的訂閱接收消息。

重要

在大部分情況下,角色指派在 Azure 中傳播需要一兩分鐘的時間。 在罕見的情況下,可能需要高達八分鐘的時間。 如果您第一次執行程式碼時收到驗證錯誤,請稍候片刻再試一次。

  1. 如果沒有在 Azure 入口網站中開啟 [服務匯流排命名空間] 頁面,請使用主要搜尋列或左側導覽找出您的服務匯流排命名空間。

  2. 在 [ 概觀] 頁面上,從左側功能表中選取 [訪問控制][IAM ]。

  3. 在 [存取控制 (IAM)] 頁面上,選取 [角色指派] 索引標籤。

  4. 從頂端功能表中選取 [+ 新增 ],然後 選取 [新增角色指派]。

    顯示如何指派角色的螢幕擷取畫面。

  5. 使用搜尋方塊,從結果篩選出所需的角色。 在此範例中,搜尋 Azure Service Bus Data Owner 並選取相符的結果。 接著,選擇 [下一步]

  6. 在 [存取權指派對象為] 下,選取 [使用者、群組或服務主體],然後選擇 [+ 選取成員]

  7. 在對話方塊中,搜尋 Microsoft Entra 使用者名稱 (通常是您的 user@domain 電子郵件地址),然後在對話方塊底部選擇 [選取]

  8. 選取 [檢閱 + 指派] 以移至最終頁面,然後再次選取 [檢閱 + 指派] 以完成此程序。

啟動 Visual Studio

您可以使用下列步驟來授權存取服務匯流排命名空間:

  1. 啟動 Visual Studio。 如果您看到 [開始使用] 視窗,請選取右窗格中的 [繼續但不開啟程式碼] 連結。

  2. 選取 Visual Studio 右上方的 [登入] 按鈕。

    螢幕擷取畫面:顯示使用 Visual Studio 來登入 Azure 的按鈕。

  3. 使用您先前指派角色的 Microsoft Entra 帳戶來登入。

    顯示選取帳戶的螢幕擷取畫面。

將訊息傳送到佇列

本節說明如何建立可將訊息傳送至服務匯流排佇列的 .NET 主控台應用程式。

注意

本快速入門提供實作簡單情節的逐步指示,說明如何將一批訊息傳送至服務匯流排佇列並接收那些訊息。 如需其他和進階情節的更多樣本,請參閱 GitHub 上的服務匯流排 .NET 樣本

建立主控台應用程式

  1. 在 Visual Studio 中,選取 [檔案] -> [新增] -> [專案] 功能表。

  2. 在 [建立新專案] 對話方塊上,執行下列步驟:如果您沒有看到此對話方塊,請在功能表上選取 [檔案]、選取 [新增],然後選取 [專案]

    1. 選取 [C#] 作為程式設計語言。

    2. 選取 [主控台] 作為應用程式的類型。

    3. 從結果清單中選取 [主控台應用程式]

    4. 然後選取下一步

      此圖顯示 [建立新專案] 對話方塊,其中已選取 [C#] 和 [主控台]

  3. 在專案名稱中輸入 QueueSender、在解決方案名稱中輸入 ServiceBusQueueQuickStart,然後選取 [下一步]

    此圖顯示 [設定新專案] 對話方塊中的解決方案和專案名稱

  4. 在 [其他資訊] 頁面上,選取 [建立] 以建立解決方案和專案。

將 NuGet 套件新增至專案

  1. 從功能表選取 [工具]>[NuGet 套件管理員]>[套件管理員主控台]

  2. 執行下列命令來安裝 Azure.Messaging.ServiceBus NuGet 套件。

    Install-Package Azure.Messaging.ServiceBus
    
  3. 執行下列命令來安裝 Azure.Identity NuGet 套件。

    Install-Package Azure.Identity
    

新增程式碼以將訊息傳送到佇列

  1. 以下列程式碼取代 Program.cs 的內容。 下節概述重要步驟,程式碼註解中有額外資訊。

    重要

    使用服務匯流排命名空間和佇列的名稱,更新程式碼片段中的預留位置值 (<NAMESPACE-NAME><QUEUE-NAME>)。

    using Azure.Messaging.ServiceBus;
    using Azure.Identity;
    
    // name of your Service Bus queue
    // the client that owns the connection and can be used to create senders and receivers
    ServiceBusClient client;
    
    // the sender used to publish messages to the queue
    ServiceBusSender sender;
    
    // number of messages to be sent to the queue
    const int numOfMessages = 3;
    
    // The Service Bus client types are safe to cache and use as a singleton for the lifetime
    // of the application, which is best practice when messages are being published or read
    // regularly.
    //
    // Set the transport type to AmqpWebSockets so that the ServiceBusClient uses the port 443. 
    // If you use the default AmqpTcp, ensure that ports 5671 and 5672 are open.
    var clientOptions = new ServiceBusClientOptions
    { 
        TransportType = ServiceBusTransportType.AmqpWebSockets
    };
    //TODO: Replace the "<NAMESPACE-NAME>" and "<QUEUE-NAME>" placeholders.
    client = new ServiceBusClient(
        "<NAMESPACE-NAME>.servicebus.windows.net",
        new DefaultAzureCredential(),
        clientOptions);
    sender = client.CreateSender("<QUEUE-NAME>");
    
    // create a batch 
    using ServiceBusMessageBatch messageBatch = await sender.CreateMessageBatchAsync();
    
    for (int i = 1; i <= numOfMessages; i++)
    {
        // try adding a message to the batch
        if (!messageBatch.TryAddMessage(new ServiceBusMessage($"Message {i}")))
        {
            // if it is too large for the batch
            throw new Exception($"The message {i} is too large to fit in the batch.");
        }
    }
    
    try
    {
        // Use the producer client to send the batch of messages to the Service Bus queue
        await sender.SendMessagesAsync(messageBatch);
        Console.WriteLine($"A batch of {numOfMessages} messages has been published to the queue.");
    }
    finally
    {
        // Calling DisposeAsync on client types is required to ensure that network
        // resources and other unmanaged objects are properly cleaned up.
        await sender.DisposeAsync();
        await client.DisposeAsync();
    }
    
    Console.WriteLine("Press any key to end the application");
    Console.ReadKey();
    
  2. 建置專案,並確定沒有任何錯誤。

  3. 執行程式,並等待確認訊息。

    A batch of 3 messages has been published to the queue
    

    重要

    在大部分情況下,角色指派在 Azure 中傳播需要一兩分鐘的時間。 在罕見的情況下,可能需要高達八分鐘的時間。 如果您第一次執行程式碼時收到驗證錯誤,請稍候片刻再試一次。

  4. 在 Azure 入口網站中遵循下列步驟:

    1. 瀏覽至您的服務匯流排命名空間。

    2. 概觀頁面上,選取底部靠中間窗格中的佇列。

      此圖顯示 Azure 入口網站中的 [服務匯流排命名空間] 頁面,其中已選取佇列。

    3. 請注意 [設定] 區段中的值

      此圖顯示已接受的訊息數量和佇列的大小。

    請注意下列值:

    • 佇列的使用中訊息計數值現在是 3。 每次執行傳送者應用程式而未擷取訊息時,這個值就會增加 3。
    • 每當應用程式將訊息新增到佇列時,佇列的目前大小就會增加。
    • 在底部 [計量] 區段的訊息圖表中,您會看到佇列有三個傳入訊息。

從佇列接收訊息

在本節中,您會建立 .NET 主控台應用程式,以接收來自佇列的訊息。

注意

本快速入門提供實作案例的逐步指示,說明如何將一批訊息傳送至服務匯流排佇列並接收那些訊息。 如需其他和進階情節的更多樣本,請參閱 GitHub 上的服務匯流排 .NET 樣本

為接收者建立專案

  1. 在 [方案總管] 視窗中,以滑鼠右鍵按一下 [ServiceBusQueueQuickStart] 解決方案,並指向 [新增],然後選取 [新增專案]
  2. 選取 [主控台應用程式],然後選取 [下一步]
  3. 輸入 [QueueReceiver] 做為專案名稱,然後選取 [建立]
  4. 在 [方案總管] 視窗中,以滑鼠右鍵按一下 [QueueReceiver],然後選取 [設定為啟動專案]

將 NuGet 套件新增至專案

  1. 從功能表選取 [工具]>[NuGet 套件管理員]>[套件管理員主控台]

  2. 針對 [預設] 專案 選取 [QueueReceiver]

    螢幕擷取畫面:顯示套件管理員主控台中選取的 QueueReceiver 專案。

  3. 執行下列命令來安裝 Azure.Messaging.ServiceBus NuGet 套件。

    Install-Package Azure.Messaging.ServiceBus
    
  4. 執行下列命令來安裝 Azure.Identity NuGet 套件。

    Install-Package Azure.Identity
    

新增程式碼以從佇列接收訊息

在本節中,您會新增程式碼以從佇列中擷取訊息。

  1. Program 類別內,新增下列程式碼:

    using System.Threading.Tasks;
    using Azure.Identity;
    using Azure.Messaging.ServiceBus;
    
    // the client that owns the connection and can be used to create senders and receivers
    ServiceBusClient client;
    
    // the processor that reads and processes messages from the queue
    ServiceBusProcessor processor;
    
  2. 將下列方法附加至 Program 類別的尾端。

    // handle received messages
    async Task MessageHandler(ProcessMessageEventArgs args)
    {
        string body = args.Message.Body.ToString();
        Console.WriteLine($"Received: {body}");
    
        // complete the message. message is deleted from the queue. 
        await args.CompleteMessageAsync(args.Message);
    }
    
    // handle any errors when receiving messages
    Task ErrorHandler(ProcessErrorEventArgs args)
    {
        Console.WriteLine(args.Exception.ToString());
        return Task.CompletedTask;
    }
    
  3. 將下列程式碼附加至 Program 類別的尾端。 下節概述重要步驟,程式碼註解中有額外資訊。

    • 使用 物件建立 DefaultAzureCredential 物件。 DefaultAzureCredential 會自動探索並使用 Visual Studio 登入的認證,向 Azure 服務匯流排進行驗證。
    • 物件上叫用 ServiceBusClient 方法,以針對特定服務匯流排佇列建立 ServiceBusProcessor 物件。
    • 指定 ServiceBusProcessor 物件的 ProcessMessageAsyncProcessErrorAsync 事件的處理常式。
    • 透過在 物件上叫用 ServiceBusProcessor 來開始處理訊息。
    • 當使用者按下按鍵結束處理時,會在 物件上叫用 ServiceBusProcessor

    重要

    使用服務匯流排命名空間和佇列的名稱,更新程式碼片段中的預留位置值 (<NAMESPACE-NAME><QUEUE-NAME>)。

    // The Service Bus client types are safe to cache and use as a singleton for the lifetime
    // of the application, which is best practice when messages are being published or read
    // regularly.
    //
    // Set the transport type to AmqpWebSockets so that the ServiceBusClient uses port 443. 
    // If you use the default AmqpTcp, make sure that ports 5671 and 5672 are open.
    
    // TODO: Replace the <NAMESPACE-NAME> placeholder
    var clientOptions = new ServiceBusClientOptions()
    {
        TransportType = ServiceBusTransportType.AmqpWebSockets
    };
    client = new ServiceBusClient(
        "<NAMESPACE-NAME>.servicebus.windows.net",
        new DefaultAzureCredential(),
        clientOptions);
    
    // create a processor that we can use to process the messages
    // TODO: Replace the <QUEUE-NAME> placeholder
    processor = client.CreateProcessor("<QUEUE-NAME>", new ServiceBusProcessorOptions());
    
    try
    {
        // add handler to process messages
        processor.ProcessMessageAsync += MessageHandler;
    
        // add handler to process any errors
        processor.ProcessErrorAsync += ErrorHandler;
    
        // start processing 
        await processor.StartProcessingAsync();
    
        Console.WriteLine("Wait for a minute and then press any key to end the processing");
        Console.ReadKey();
    
        // stop processing 
        Console.WriteLine("\nStopping the receiver...");
        await processor.StopProcessingAsync();
        Console.WriteLine("Stopped receiving messages");
    }
    finally
    {
        // Calling DisposeAsync on client types is required to ensure that network
        // resources and other unmanaged objects are properly cleaned up.
        await processor.DisposeAsync();
        await client.DisposeAsync();
    }
    
  4. 完成的 Program 類別應該符合下列程式碼:

    using System.Threading.Tasks;
    using Azure.Messaging.ServiceBus;
    using Azure.Identity;
    
    // the client that owns the connection and can be used to create senders and receivers
    ServiceBusClient client;
    
    // the processor that reads and processes messages from the queue
    ServiceBusProcessor processor;
    
    // The Service Bus client types are safe to cache and use as a singleton for the lifetime
    // of the application, which is best practice when messages are being published or read
    // regularly.
    //
    // Set the transport type to AmqpWebSockets so that the ServiceBusClient uses port 443.
    // If you use the default AmqpTcp, make sure that ports 5671 and 5672 are open.
    
    // TODO: Replace the <NAMESPACE-NAME> and <QUEUE-NAME> placeholders
    var clientOptions = new ServiceBusClientOptions() 
    {
        TransportType = ServiceBusTransportType.AmqpWebSockets
    };
    client = new ServiceBusClient("<NAMESPACE-NAME>.servicebus.windows.net", 
        new DefaultAzureCredential(), clientOptions);
    
    // create a processor that we can use to process the messages
    // TODO: Replace the <QUEUE-NAME> placeholder
    processor = client.CreateProcessor("<QUEUE-NAME>", new ServiceBusProcessorOptions());
    
    try
    {
        // add handler to process messages
        processor.ProcessMessageAsync += MessageHandler;
    
        // add handler to process any errors
        processor.ProcessErrorAsync += ErrorHandler;
    
        // start processing 
        await processor.StartProcessingAsync();
    
        Console.WriteLine("Wait for a minute and then press any key to end the processing");
        Console.ReadKey();
    
        // stop processing 
        Console.WriteLine("\nStopping the receiver...");
        await processor.StopProcessingAsync();
        Console.WriteLine("Stopped receiving messages");
    }
    finally
    {
        // Calling DisposeAsync on client types is required to ensure that network
        // resources and other unmanaged objects are properly cleaned up.
        await processor.DisposeAsync();
        await client.DisposeAsync();
    }
    
    // handle received messages
    async Task MessageHandler(ProcessMessageEventArgs args)
    {
        string body = args.Message.Body.ToString();
        Console.WriteLine($"Received: {body}");
    
        // complete the message. message is deleted from the queue. 
        await args.CompleteMessageAsync(args.Message);
    }
    
    // handle any errors when receiving messages
    Task ErrorHandler(ProcessErrorEventArgs args)
    {
        Console.WriteLine(args.Exception.ToString());
        return Task.CompletedTask;
    }
    
  5. 建置專案,並確定沒有任何錯誤。

  6. 執行接收者應用程式。 您應該會看到收到的訊息。 按任意鍵可停止接收者和應用程式。

    Wait for a minute and then press any key to end the processing
    Received: Message 1
    Received: Message 2
    Received: Message 3
    
    Stopping the receiver...
    Stopped receiving messages
    
  7. 再次查看入口網站。 如果您看不到0訊息為 ,請等候幾分鐘再重新整理頁面。

    • 作用中訊息計數和目前大小值現在是 0

    • 在底部 [計量] 區段的訊息圖表中,您會看到佇列有三個內送郵件和三個外寄郵件。

      螢幕擷取畫面:顯示接收後的作用中訊息和大小。

其他資訊

請參閱下列文件和範例:

清除資源

在 Azure 入口網站中瀏覽至您的服務匯流排命名空間,然後在 Azure 入口網站上選取 [刪除],以刪除其中的命名空間和佇列。

請參閱開始使用 Azure 服務匯流排 主題和訂用帳戶 (.NET)