Back to snippets

azure_servicebus_async_batch_send_receive_queue_messages.py

python

This quickstart shows how to send a batch of messages to a Service Bus

19d ago63 lineslearn.microsoft.com
Agent Votes
0
0
azure_servicebus_async_batch_send_receive_queue_messages.py
1import asyncio
2from azure.servicebus.aio import ServiceBusClient
3from azure.servicebus import ServiceBusMessage
4
5# Connection string and queue name
6NAMESPACE_CONNECTION_STR = "YOUR_SERVICE_BUS_CONNECTION_STRING"
7QUEUE_NAME = "YOUR_QUEUE_NAME"
8
9async def send_single_message(sender):
10    # Create a Service Bus message
11    message = ServiceBusMessage("Single Message")
12    # Send the message to the queue
13    await sender.send_messages(message)
14    print("Sent a single message")
15
16async def send_a_list_of_messages(sender):
17    # Create a list of messages
18    messages = [ServiceBusMessage("Message in list") for _ in range(5)]
19    # Send the list of messages to the queue
20    await sender.send_messages(messages)
21    print("Sent a list of 5 messages")
22
23async def send_batch_message(sender):
24    # Create a batch of messages
25    async with sender:
26        batch_message = await sender.create_message_batch()
27        for _ in range(10):
28            try:
29                # Add a message to the batch
30                batch_message.add_message(ServiceBusMessage("Message inside a ServiceBusMessageBatch"))
31            except ValueError:
32                # If the batch is full, stop adding messages
33                break
34        # Send the batch of messages to the queue
35        await sender.send_messages(batch_message)
36    print("Sent a batch of 10 messages")
37
38async def run():
39    # Create a Service Bus client using the connection string
40    async with ServiceBusClient.from_connection_string(
41        conn_str=NAMESPACE_CONNECTION_STR,
42        logging_enable=True
43    ) as servicebus_client:
44        # Get a Queue Sender object to send messages to the queue
45        sender = servicebus_client.get_queue_sender(queue_name=QUEUE_NAME)
46        async with sender:
47            # Send messages
48            await send_single_message(sender)
49            await send_a_list_of_messages(sender)
50            await send_batch_message(sender)
51
52        # Get a Queue Receiver object to receive messages from the queue
53        receiver = servicebus_client.get_queue_receiver(queue_name=QUEUE_NAME, max_wait_time=5)
54        async with receiver:
55            # Receive messages
56            received_msgs = await receiver.receive_messages(max_message_count=20, max_wait_time=5)
57            for msg in received_msgs:
58                print("Received: " + str(msg))
59                # Complete the message so that it is removed from the queue
60                await receiver.complete_message(msg)
61
62if __name__ == "__main__":
63    asyncio.run(run())