快速入門:透過 Python 使用服務匯流排主題和訂用帳戶Quickstart: Use Service Bus topics and subscriptions with Python

本文說明如何使用 Python 搭配服務匯流排主題和訂用帳戶。This article describes how to use Python with Azure Service Bus topics and subscriptions. 這些範例會使用 Azure Python SDK 套件來執行下列動作:The samples use the Azure Python SDK package to:

  • 在主題中建立主題和訂用帳戶Create topics and subscriptions to topics
  • 建立訂用帳戶篩選條件和規則Create subscription filters and rules
  • 將訊息傳送至主題Send messages to topics
  • 接收來自訂用帳戶的訊息Receive messages from subscriptions
  • 刪除主題和訂用帳戶Delete topics and subscriptions

必要條件Prerequisites

建立 ServiceBusService 物件Create a ServiceBusService object

ServiceBusService 物件可讓您使用主題及其訂用帳戶。A ServiceBusService object lets you work with topics and subscriptions to topics. 若要以程式設計方式存取服務匯流排,請在 Python 檔案的頂端附近新增下列程式碼行:To programmatically access Service Bus, add the following line near the top of your Python file:

from azure.servicebus.control_client import ServiceBusService, Message, Topic, Rule, DEFAULT_RULE_NAME

新增下列程式碼以建立 ServiceBusService 物件。Add the following code to create a ServiceBusService object. 請使用您的服務匯流排命名空間名稱、共用存取簽章 (SAS) 金鑰名稱和主要金鑰值來取代 <namespace><sharedaccesskeyname><sharedaccesskeyvalue>Replace <namespace>, <sharedaccesskeyname>, and <sharedaccesskeyvalue> with your Service Bus namespace name, Shared Access Signature (SAS) key name, and primary key value. 您可以在 Azure 入口網站中,於服務匯流排命名空間的 [共用存取原則] 之下找到這些值。You can find these values under Shared access policies in your Service Bus namespace in the Azure portal.

bus_service = ServiceBusService(
    service_namespace='<namespace>',
    shared_access_key_name='<sharedaccesskeyname>',
    shared_access_key_value='<sharedaccesskeyvalue>')

建立主題Create a topic

下列程式碼會使用 create_topic 方法,以預設設定建立名為 mytopic 的服務匯流排主題:The following code uses the create_topic method to create a Service Bus topic called mytopic, with default settings:

bus_service.create_topic('mytopic')

您可以使用主題選項來覆寫預設主題設定,例如訊息存留時間 (TTL) 或主題大小上限。You can use topic options to override default topic settings, such as message time to live (TTL) or maximum topic size. 下列範例會建立名為 mytopic 的主題,其主題大小上限為 5 GB 且預設訊息 TTL 為一分鐘:The following example creates a topic named mytopic with a maximum topic size of 5 GB and default message TTL of one minute:

topic_options = Topic()
topic_options.max_size_in_megabytes = '5120'
topic_options.default_message_time_to_live = 'PT1M'

bus_service.create_topic('mytopic', topic_options)

建立訂用帳戶Create subscriptions

您也可以使用 ServiceBusService 物件來建立主題的訂用帳戶。You also use the ServiceBusService object to create subscriptions to topics. 訂用帳戶可使用篩選條件來限制傳遞至其虛擬佇列的訊息集。A subscription can have a filter to restrict the message set delivered to its virtual queue. 如果您未指定篩選條件,新的訂用帳戶會使用預設 MatchAll 篩選條件,其會將所有發佈至主題的訊息放入訂用帳戶的虛擬佇列中。If you don't specify a filter, new subscriptions use the default MatchAll filter, which places all messages published to the topic into the subscription's virtual queue. 下列範例會對名為 AllMessagesmytopic 建立訂用帳戶,其使用 MatchAll 篩選條件:The following example creates a subscription to mytopic named AllMessages that uses the MatchAll filter:

bus_service.create_subscription('mytopic', 'AllMessages')

將篩選條件使用於訂用帳戶Use filters with subscriptions

使用 ServiceBusService 物件的 create_rule 方法,篩選出現在訂用帳戶中的訊息。Use the create_rule method of the ServiceBusService object to filter the messages that appear in a subscription. 您可以在建立訂用帳戶時指定規則,或將規則新增至現有的訂用帳戶。You can specify rules when you create the subscription, or add rules to existing subscriptions.

最具彈性的篩選條件類型是 SqlFilter,其使用 SQL-92 的子集。The most flexible type of filter is a SqlFilter, which uses a subset of SQL-92. SQL 篩選條件會根據發佈至主題的訊息屬性運作。SQL filters operate based on the properties of messages published to the topic. 如需可與 SQL 篩選條件搭配使用的運算式詳細資訊,請參閱 SqlFilter.SqlExpression 語法。For more information about the expressions you can use with a SQL filter, see the SqlFilter.SqlExpression syntax.

由於 MatchAll 預設篩選條件會自動套用至所有新的訂用帳戶,因此您必須先從您要篩選的訂用帳戶中移除該篩選條件,否則 MatchAll 會覆寫您指定的任何其他篩選條件。Because the MatchAll default filter applies automatically to all new subscriptions, you must remove it from subscriptions you want to filter, or MatchAll will override any other filters you specify. 您可以使用 ServiceBusService 物件的 delete_rule 方法移除預設規則。You can remove the default rule by using the delete_rule method of the ServiceBusService object.

下列範例會對名為 HighMessagesmytopic 建立訂用帳戶,其使用名為 HighMessageFilterSqlFilter 規則。The following example creates a subscription to mytopic named HighMessages, with a SqlFilter rule named HighMessageFilter. HighMessageFilter 規則只會選取自訂 messageposition 屬性大於 3 的訊息:The HighMessageFilter rule selects only messages with a custom messageposition property greater than 3:

bus_service.create_subscription('mytopic', 'HighMessages')

rule = Rule()
rule.filter_type = 'SqlFilter'
rule.filter_expression = 'messageposition > 3'

bus_service.create_rule('mytopic', 'HighMessages', 'HighMessageFilter', rule)
bus_service.delete_rule('mytopic', 'HighMessages', DEFAULT_RULE_NAME)

下列範例會對名為 LowMessagesmytopic 建立訂用帳戶,其使用名為 LowMessageFilterSqlFilter 規則。The following example creates a subscription to mytopic named LowMessages, with a SqlFilter rule named LowMessageFilter. LowMessageFilter 規則只會選取 messageposition 屬性小於或等於 3 的訊息:The LowMessageFilter rule selects only messages with a messageposition property less than or equal to 3:

bus_service.create_subscription('mytopic', 'LowMessages')

rule = Rule()
rule.filter_type = 'SqlFilter'
rule.filter_expression = 'messageposition <= 3'

bus_service.create_rule('mytopic', 'LowMessages', 'LowMessageFilter', rule)
bus_service.delete_rule('mytopic', 'LowMessages', DEFAULT_RULE_NAME)

AllMessagesHighMessagesLowMessages 全部生效後,傳送至 mytopic 的訊息一律會傳遞給 AllMessages 訂用帳戶的接收者。With AllMessages, HighMessages, and LowMessages all in effect, messages sent to mytopic are always delivered to receivers of the AllMessages subscription. 視訊息的 messageposition 屬性值而定,訊息也可選擇性地傳遞至 HighMessagesLowMessages 訂用帳戶。Messages are also selectively delivered to the HighMessages or LowMessages subscription, depending on the message's messageposition property value.

傳送訊息至主題Send messages to a topic

應用程式會使用 ServiceBusService 物件的 send_topic_message 方法,將訊息傳送至服務匯流排主題。Applications use the send_topic_message method of the ServiceBusService object to send messages to a Service Bus topic.

下列範例會將五則測試訊息傳送至 mytopic 主題。The following example sends five test messages to the mytopic topic. 自訂 messageposition 屬性值取決於迴圈的反覆運算,可決定哪些訂用帳戶會接收訊息。The custom messageposition property value depends on the iteration of the loop, and determines which subscriptions receive the messages.

for i in range(5):
    msg = Message('Msg {0}'.format(i).encode('utf-8'),
                  custom_properties={'messageposition': i})
    bus_service.send_topic_message('mytopic', msg)

訊息大小限制和配額Message size limits and quotas

服務匯流排主題支援的訊息大小上限:在標準層中為 256 KB 以及在進階層中為 1 MB。Service Bus topics support a maximum message size of 256 KB in the Standard tier and 1 MB in the Premium tier. 標頭 (包含標準和自訂應用程式屬性) 可以容納 64 KB 的大小上限。The header, which includes the standard and custom application properties, can have a maximum size of 64 KB. 主題可保存的訊息數目沒有限制,但主題所保存的總訊息大小有最高限制。There's no limit on the number of messages a topic can hold, but there's a cap on the total size of the messages the topic holds. 您可以在建立主題時定義其大小,其上限為 5 GB。You can define topic size at creation time, with an upper limit of 5 GB.

如需有關配額的詳細資訊,請參閱 服務匯流排配額For more information about quotas, see Service Bus quotas.

自訂用帳戶接收訊息Receive messages from a subscription

應用程式會在 ServiceBusService 物件上使用 receive_subscription_message 方法,以接收來自訂用帳戶的訊息。Applications use the receive_subscription_message method on the ServiceBusService object to receive messages from a subscription. 下列範例會從 LowMessages 的訂用帳戶接收訊息,並在讀取後將其刪除:The following example receives messages from the LowMessages subscription and deletes them as they're read:

msg = bus_service.receive_subscription_message('mytopic', 'LowMessages', peek_lock=False)
print(msg.body)

receive_subscription_message 的選擇性 peek_lock 參數會決定在讀取訊息後,服務匯流排是否會從訂用帳戶中刪除訊息。The optional peek_lock parameter of receive_subscription_message determines whether Service Bus deletes messages from the subscription as they're read. 預設的訊息接收模式為 PeekLock,或設為 Truepeek_lock,其會讀取 (預覽) 並鎖定訊息,而不需從訂用帳戶中刪除訊息。The default mode for message receiving is PeekLock, or peek_lock set to True, which reads (peeks) and locks messages without deleting them from the subscription. 接著,必須明確地完成每則訊息,才能將它從訂用帳戶中移除。Each message must then be explicitly completed to remove it from the subscription.

若要在讀取訊息後從訂用帳戶中刪除訊息,您可以將 peek_lock 參數設定為 False,如上述範例所示。To delete messages from the subscription as they're read, you can set the peek_lock parameter to False, as in the preceding example. 在接收作業中刪除訊息是最簡單的模型,且應用程式可在發生失敗時容忍遺失訊息,才能運作良好。Deleting messages as part of the receive operation is the simplest model, and works fine if the application can tolerate missing messages if there's a failure. 若要了解此行為,請考慮應用程式發出接收要求,接著在處理此要求之前當機的案例。To understand this behavior, consider a scenario in which the application issues a receive request and then crashes before processing it. 如果訊息在收到時遭到刪除,當應用程式重新啟動並再度開始取用訊息時,其會在當機前遺失所收到的訊息。If the message was deleted on being received, when the application restarts and begins consuming messages again, it has missed the message it received before the crash.

如果應用程式無法容忍遺失訊息,則接收會成為兩階段的作業。If your application can't tolerate missed messages, the receive becomes a two-stage operation. PeekLock 會尋找要取用的下一個訊息、將其鎖定以防止其他取用者接收此訊息,然後將它傳回到應用程式。PeekLock finds the next message to be consumed, locks it to prevent other consumers from receiving it, and returns it to the application. 在處理或儲存此訊息之後,應用程式會在 Message 物件上呼叫 complete 方法,以完成接收程序的第二個階段。After processing or storing the message, the application completes the second stage of the receive process by calling the complete method on the Message object. complete 方法會將訊息標示為已取用,並將其從訂用帳戶中移除。The complete method marks the message as being consumed and removes it from the subscription.

下列範例示範 peek lock 案例:The following example demonstrates a peek lock scenario:

msg = bus_service.receive_subscription_message('mytopic', 'LowMessages', peek_lock=True)
if msg.body is not None:
    print(msg.body)
    msg.complete()

處理應用程式當機與無法讀取的訊息Handle application crashes and unreadable messages

服務匯流排提供一種功能,可協助您從應用程式的錯誤或處理訊息的問題中順利復原。Service Bus provides functionality to help you gracefully recover from errors in your application or difficulties processing a message. 如果接收者應用程式因為某些原因而無法處理訊息,其可在 Message 物件上呼叫 unlock 方法。If a receiver application can't process a message for some reason, it can call the unlock method on the Message object. 服務匯流排會將訂用帳戶中的訊息解除鎖定,讓此訊息可由相同或其他取用應用程式重新接收。Service Bus unlocks the message within the subscription and makes it available to be received again, either by the same or another consuming application.

訂用帳戶內鎖定的訊息也會逾時。There's also a timeout for messages locked within the subscription. 如果應用程式無法在鎖定逾時到期前處理訊息 (例如,若應用程式當機),則服務匯流排會自動解除鎖定訊息,並讓系統可以重新接收訊息。If an application fails to process a message before the lock timeout expires, for example if the application crashes, Service Bus unlocks the message automatically and makes it available to be received again.

如果應用程式在處理訊息後但呼叫 complete 方法前當機,則會在應用程式重新啟動時將訊息重新傳遞給該應用程式。If an application crashes after processing a message but before calling the complete method, the message will be redelivered to the application when it restarts. 這種行為通常稱為「至少處理一次」 。This behavior is often called At-least-once Processing. 每則訊息至少會處理一次;但在特定狀況下,可能會重新傳遞相同訊息。Each message is processed at least once, but in certain situations the same message may be redelivered. 如果您的案例無法容許重複處理,您可以使用訊息的 MessageId 屬性,其會在各傳遞嘗試中保持不變,以處理重複的訊息傳遞。If your scenario can't tolerate duplicate processing, you can use the MessageId property of the message, which remains constant across delivery attempts, to handle duplicate message delivery.

刪除主題和訂用帳戶Delete topics and subscriptions

若要刪除主題和訂用帳戶,請使用 Azure 入口網站delete_topic 方法。To delete topics and subscriptions, use the Azure portal or the delete_topic method. 下列程式碼會刪除名為 mytopic 的主題:The following code deletes the topic named mytopic:

bus_service.delete_topic('mytopic')

刪除主題同時會刪除主題的所有訂用帳戶。Deleting a topic deletes all subscriptions to the topic. 您也可以單獨刪除訂用帳戶。You can also delete subscriptions independently. 下列程式碼會從 mytopic 主題刪除名為 HighMessages 的訂用帳戶:The following code deletes the subscription named HighMessages from the mytopic topic:

bus_service.delete_subscription('mytopic', 'HighMessages')

根據預設,主題和訂用帳戶會持續存在,直到您將其刪除為止。By default, topics and subscriptions are persistent, and exist until you delete them. 若要在經過特定一段時間之後自動刪除訂用帳戶,您可以在訂用帳戶上設定 auto_delete_on_idle 參數。To automatically delete subscriptions after a certain time period elapses, you can set the auto_delete_on_idle parameter on the subscription.

提示

您可以使用服務匯流排總管來管理服務匯流排資源。You can manage Service Bus resources with Service Bus Explorer. 服務匯流排總管可讓您連線到服務匯流排命名空間,並輕鬆地管理傳訊實體。Service Bus Explorer lets you connect to a Service Bus namespace and easily administer messaging entities. 此工具提供進階的功能 (例如匯入/匯出功能),以及測試主題、佇列、訂用帳戶、轉送服務、通知中樞和事件中樞的能力。The tool provides advanced features like import/export functionality and the ability to test topics, queues, subscriptions, relay services, notification hubs, and event hubs.

後續步驟Next steps

了解基本的服務匯流排主題之後,請參考下列連結以取得更多資訊:Now that you've learned the basics of Service Bus topics, follow these links to learn more: