在 Azure 服務匯流排佇列 (Python) 中傳送和接收訊息Send messages to and receive messages from Azure Service Bus queues (Python)

本文示範如何使用 Python 傳送及接收 Azure 服務匯流排中的訊息。This article shows you how to use Python to send messages to, and receive messages from Azure Service Bus queues.

先決條件Prerequisites

傳送訊息至佇列Send messages to a queue

  1. 新增下列 Import 陳述式。Add the following import statement.

    from azure.servicebus import ServiceBusClient, ServiceBusMessage
    
  2. 新增下列常數。Add the following constants.

    CONNECTION_STR = "<NAMESPACE CONNECTION STRING>"
    QUEUE_NAME = "<QUEUE NAME>"
    

    重要

    • <NAMESPACE CONNECTION STRING> 取代為服務匯流排命名空間的連接字串。Replace <NAMESPACE CONNECTION STRING> with the connection string for your Service Bus namespace.
    • <QUEUE NAME> 取代為佇列名稱。Replace <QUEUE NAME> with the name of the queue.
  3. 新增方法來傳送單一訊息。Add a method to send a single message.

    def send_single_message(sender):
        # create a Service Bus message
        message = ServiceBusMessage("Single Message")
        # send the message to the queue
        sender.send_messages(message)
        print("Sent a single message")
    

    傳送者是物件,可作為您所建立之佇列的用戶端。The sender is an object that acts as a client for the queue you created. 您稍後會建立此項目,並以引數的形式傳送至此函式。You'll create it later and send as an argument to this function.

  4. 新增方法來傳送訊息清單。Add a method to send a list of messages.

    def send_a_list_of_messages(sender):
        # create a list of messages
        messages = [ServiceBusMessage("Message in list") for _ in range(5)]
        # send the list of messages to the queue
        sender.send_messages(messages)
        print("Sent a list of 5 messages")
    
  5. 新增方法來傳送訊息批次。Add a method to send a batch of messages.

    def send_batch_message(sender):
        # create a batch of messages
        batch_message = sender.create_message_batch()
        for _ in range(10):
            try:
                # add a message to the batch
                batch_message.add_message(ServiceBusMessage("Message inside a ServiceBusMessageBatch"))
            except ValueError:
                # ServiceBusMessageBatch object reaches max_size.
                # New ServiceBusMessageBatch object can be created here to send more data.
                break
        # send the batch of messages to the queue
        sender.send_messages(batch_message)
        print("Sent a batch of 10 messages")
    
  6. 建立服務匯流排用戶端,然後建立傳送訊息的佇列傳送者物件。Create a Service Bus client and then a queue sender object to send messages.

    # create a Service Bus client using the connection string
    servicebus_client = ServiceBusClient.from_connection_string(conn_str=CONNECTION_STR, logging_enable=True)
    with servicebus_client:
        # get a Queue Sender object to send messages to the queue
        sender = servicebus_client.get_queue_sender(queue_name=QUEUE_NAME)
        with sender:
            # send one message        
            send_single_message(sender)
            # send a list of messages
            send_a_list_of_messages(sender)
            # send a batch of messages
            send_batch_message(sender)
    
    print("Done sending messages")
    print("-----------------------")
    

從佇列接收訊息Receive messages from a queue

在列印陳述式之後新增下列程式碼。Add the following code after the print statement. 此程式碼會持續收到新訊息,直到 5 (max_wait_time) 秒未收到任何新訊息為止。This code continually receives new messages until it doesn't receive any new messages for 5 (max_wait_time) seconds.

with servicebus_client:
    # get the Queue Receiver object for the queue
    receiver = servicebus_client.get_queue_receiver(queue_name=QUEUE_NAME, max_wait_time=5)
    with receiver:
        for msg in receiver:
            print("Received: " + str(msg))
            # complete the message so that the message is removed from the queue
            receiver.complete_message(msg)

完整程式碼Full code

# import os
from azure.servicebus import ServiceBusClient, ServiceBusMessage

CONNECTION_STR = "<NAMESPACE CONNECTION STRING>"
QUEUE_NAME = "<QUEUE NAME>"

def send_single_message(sender):
    message = ServiceBusMessage("Single Message")
    sender.send_messages(message)
    print("Sent a single message")

def send_a_list_of_messages(sender):
    messages = [ServiceBusMessage("Message in list") for _ in range(5)]
    sender.send_messages(messages)
    print("Sent a list of 5 messages")

def send_batch_message(sender):
    batch_message = sender.create_message_batch()
    for _ in range(10):
        try:
            batch_message.add_message(ServiceBusMessage("Message inside a ServiceBusMessageBatch"))
        except ValueError:
            # ServiceBusMessageBatch object reaches max_size.
            # New ServiceBusMessageBatch object can be created here to send more data.
            break
    sender.send_messages(batch_message)
    print("Sent a batch of 10 messages")

servicebus_client = ServiceBusClient.from_connection_string(conn_str=CONNECTION_STR, logging_enable=True)

with servicebus_client:
    sender = servicebus_client.get_queue_sender(queue_name=QUEUE_NAME)
    with sender:
        send_single_message(sender)
        send_a_list_of_messages(sender)
        send_batch_message(sender)

print("Done sending messages")
print("-----------------------")

with servicebus_client:
    receiver = servicebus_client.get_queue_receiver(queue_name=QUEUE_NAME, max_wait_time=5)
    with receiver:
        for msg in receiver:
            print("Received: " + str(msg))
            receiver.complete_message(msg)

執行應用程式Run the app

執行應用程式時會看到下列輸出:When you run the application, you should see the following output:

Sent a single message
Sent a list of 5 messages
Sent a batch of 10 messages
Done sending messages
-----------------------
Received: Single Message
Received: Message in list
Received: Message in list
Received: Message in list
Received: Message in list
Received: Message in list
Received: Message inside a ServiceBusMessageBatch
Received: Message inside a ServiceBusMessageBatch
Received: Message inside a ServiceBusMessageBatch
Received: Message inside a ServiceBusMessageBatch
Received: Message inside a ServiceBusMessageBatch
Received: Message inside a ServiceBusMessageBatch
Received: Message inside a ServiceBusMessageBatch
Received: Message inside a ServiceBusMessageBatch
Received: Message inside a ServiceBusMessageBatch
Received: Message inside a ServiceBusMessageBatch

瀏覽至 Azure 入口網站中您的服務匯流排命名空間。In the Azure portal, navigate to your Service Bus namespace. 概觀 頁面上,確認 傳入傳出 訊息計數為 16。On the Overview page, verify that the incoming and outgoing message counts are 16. 如果未看到此計數,請等候幾分鐘後重新整理頁面。If you don't see the counts, refresh the page after waiting for a few minutes.

傳入和傳出訊息計數

選取此 概觀 頁面上的佇列,瀏覽至 服務匯流排佇列 頁面。Select the queue on this Overview page to navigate to the Service Bus Queue page. 您也會在此頁面上看到 傳入傳出 訊息計數。You can also see the incoming and outgoing message count on this page. 您也會看到其他資訊,例如佇列的 目前大小作用中訊息計數 等等。You also see other information such as the current size of the queue and active message count.

佇列詳細資料

後續步驟Next steps

請參閱下列文件和範例:See the following documentation and samples: