Azure Service Bus Client Library for Python
The `azure-servicebus` library (version 7.14.3) is the Microsoft Azure Service Bus client for Python. It provides high-performance, cloud-managed messaging capabilities for real-time and fault-tolerant communication between distributed senders and receivers. It supports various asynchronous messaging patterns, including structured first-in-first-out messaging, publish/subscribe, and scalable queues and topics. The library is actively maintained with regular releases.
Warnings
- breaking Major breaking changes occurred between versions v0.50.x and v7.x of the `azure-servicebus` library. The API surface was significantly revamped to align with the Azure SDK guidelines, including new client constructors, authentication patterns (shifting to `azure-identity`), and object models for messages and clients.
- gotcha Message or session locks can be lost before their expiration time due to transient network failures, network outages, or the service's 10-minute idle timeout. If a message is received but not settled before the link detaches, it cannot be settled upon reconnection, potentially leading to redelivery or dead-lettering.
- gotcha Creating multiple `ServiceBusClient` instances within an application can lead to socket exhaustion errors, as each client typically establishes a new AMQP connection. This can deplete available network resources and cause connectivity issues.
- gotcha Azure Service Bus enforces quotas on messaging operations. Exceeding these quotas can result in throttling, causing send and receive operations to slow down or fail with `ServiceBusy` exceptions.
- gotcha Errors like 'brokeredmessage has been disposed' or 'cannot access a disposed object' indicate that an attempt was made to interact with a message or client object that has already been closed or disposed. This often occurs when managing client lifetimes incorrectly or trying to settle a message that has already been settled.
Install
-
pip install azure-servicebus azure-identity aiohttp
Imports
- ServiceBusClient
from azure.servicebus import ServiceBusClient
- ServiceBusMessage
from azure.servicebus import ServiceBusMessage
- ServiceBusReceivedMessage
from azure.servicebus import ServiceBusReceivedMessage
- DefaultAzureCredential
from azure.identity import DefaultAzureCredential
Quickstart
import os
from azure.servicebus import ServiceBusClient, ServiceBusMessage
# Retrieve connection string from environment variable
CONNECTION_STR = os.environ.get('AZURE_SERVICEBUS_CONNECTION_STRING', 'Endpoint=sb://<YOUR_NAMESPACE>.servicebus.windows.net/;SharedAccessKeyName=<KEY_NAME>;SharedAccessKey=<KEY_VALUE>')
QUEUE_NAME = os.environ.get('AZURE_SERVICEBUS_QUEUE_NAME', 'myqueue')
def send_single_message():
servicebus_client = ServiceBusClient.from_connection_string(conn_str=CONNECTION_STR)
with servicebus_client: # automatically closes client on exit
sender = servicebus_client.get_queue_sender(queue_name=QUEUE_NAME)
with sender: # automatically closes sender on exit
message = ServiceBusMessage("Hello, Service Bus!")
sender.send_messages(message)
print(f"Sent a single message to queue: {QUEUE_NAME}")
def receive_single_message():
servicebus_client = ServiceBusClient.from_connection_string(conn_str=CONNECTION_STR)
with servicebus_client:
receiver = servicebus_client.get_queue_receiver(queue_name=QUEUE_NAME, max_wait_time=5) # max_wait_time in seconds
with receiver:
received_messages = receiver.receive_messages(max_messages=1)
for msg in received_messages:
print(f"Received message: {msg.body}")
# Complete the message to remove it from the queue
receiver.complete_message(msg)
print("Message completed.")
if not received_messages:
print(f"No messages received from queue: {QUEUE_NAME}")
if __name__ == '__main__':
# Ensure AZURE_SERVICEBUS_CONNECTION_STRING and AZURE_SERVICEBUS_QUEUE_NAME are set as environment variables
# or replace placeholder values in the CONNECTION_STR and QUEUE_NAME variables.
print("Sending message...")
send_single_message()
print("Receiving message...")
receive_single_message()