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

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

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

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

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

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

    注意

    本快速入門提供逐步指示,以實作將一批訊息傳送至 服務匯流排 佇列,然後接收訊息的簡單案例。 如需 .NET 用戶端連結庫的概觀,請參閱 Azure 服務匯流排 .NET 的用戶端連結庫。 如需更多範例,請參閱 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. 在左側導覽列中,從類別清單中選取 [整合],將滑鼠停留在 服務匯流排 上方,然後選取 + 服務匯流排 圖格上的按鈕。

    Image showing selection of Create a resource, Integration, and then Service Bus in the menu.

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

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

    2. 針對 [ 資源群組],選擇命名空間將存留在其中的現有資源群組,或建立新的資源群組。

    3. 輸入命名空間的名稱。 命名空間名稱應遵守下列命名慣例:

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

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

      重要

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

      如果您選取 進階版 定價層,請指定傳訊單位數目。 進階層會在 CPU 和記憶體層級提供資源隔離,讓每個工作負載以隔離方式執行。 此資源容器稱為傳訊單位。 進階命名空間至少有一個傳訊單位。 您可以為每個 服務匯流排 進階版 命名空間選取 1、2、4、8 或 16 個傳訊單位。 如需詳細資訊,請參閱 服務匯流排 進階版 傳訊

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

      Image showing the Create a namespace page

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

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

    Image showing the deployment succeeded page with the Go to resource link.

  6. 您會看到服務總線命名空間的首頁。

    Image showing the home page of the Service Bus namespace created.

在 Azure 入口網站 中建立佇列

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

  2. 在 [ 佇列] 頁面上,選取 工具列上的 [+ 佇列 ]。

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

  4. 現在,選取 [ 建立]。

    Image showing creation of a queue in the portal

重要

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

向 Azure 驗證應用程式

本快速入門示範兩種連線到 Azure 服務匯流排 的方式:密碼和 連接字串

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

第二個選項示範如何使用 連接字串 來連線到 服務匯流排 命名空間。 如果您不熟悉 Azure,您可能會發現 連接字串 選項更容易遵循。 我們建議在真實世界應用程式和生產環境中使用無密碼選項。 如需詳細資訊,請參閱驗證與授權。 您也可以在概 觀頁面上深入瞭解無密碼驗證。

將角色指派給 Microsoft Entra 使用者

在本機開發時,請確定連線到 Azure 服務匯流排 的用戶帳戶具有正確的許可權。 您需要 Azure 服務匯流排 數據擁有者角色,才能傳送和接收訊息。 若要指派此角色,您需要使用者存取 管理員 istrator 角色,或包含Microsoft.Authorization/roleAssignments/write動作的另一個角色。 您可以使用 Azure 入口網站、Azure CLI 或 Azure PowerShell,將 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. 從頂端功能表選取 [+ 新增],然後從產生的下拉功能表中選取 [新增角色指派]

    A screenshot showing how to assign a role.

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

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

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

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

啟動 Visual Studio 並登入 Azure

您可以使用下列步驟來授權服務總線命名空間的存取權:

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

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

    Screenshot showing a button to sign in to Azure using Visual Studio.

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

    Screenshot showing the account selection.

將訊息傳送至佇列

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

注意

本快速入門提供逐步指示,以實作將一批訊息傳送至 服務匯流排 佇列,然後接收訊息的簡單案例。 如需其他和進階案例的更多範例,請參閱 GitHub 上的 服務匯流排 .NET 範例。

建立主控台應用程式

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

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

    1. 針對程式設計語言選擇 C#

    2. 針對應用程式類型選取 [ 主控台 ]。

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

    4. 然後選取下一步

      Image showing the Create a new project dialog box with C# and Console selected

  3. 輸入 QueueSender 以取得專案名稱 、ServiceBusQueueQuickStart 以取得方案名稱,然後選取 [ 下一步]。

    Image showing the solution and project names in the Configure your new project dialog box

  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. 在 [概 觀] 頁面上,選取底部窗格中的佇列。

      Image showing the Service Bus Namespace page in the Azure portal with the queue selected.

    3. 請注意 Essentials 區段中的值

      Image showing the number of messages received and the size of the queue.

    請注意下列值:

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

從佇列接收訊息

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

注意

本快速入門提供逐步指示,以實作將一批訊息傳送至 服務匯流排 佇列,然後接收訊息的案例。 如需其他和進階案例的詳細資訊,請參閱 GitHub 上的 服務匯流排 .NET 範例。

建立接收者的專案

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

將 NuGet 套件新增至專案

  1. 從功能表中選取 [工具>NuGet 封裝管理員> 封裝管理員 控制台]。

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

    Screenshot showing QueueReceiver project selected in the Package Manager Console.

  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 結尾。 下一節將概述重要步驟,並在程式代碼批注中提供其他資訊。

    重要

    使用您 服務匯流排 命名空間和佇列的名稱,更新代碼段中的佔位元值 (<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

    • 在底部 [計量] 區段的 [訊息] 圖表中,您可以看到佇列有三個傳入訊息和三個傳出訊息。

      Screenshot showing active messages and size after receive.

清除資源

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

另請參閱

請參閱下列檔和範例:

下一步