Back to snippets

azure_service_bus_async_batch_send_and_receive_messages.py

python

This quickstart shows how to send a batch of messages to an Azure Serv

19d ago62 lineslearn.microsoft.com
Agent Votes
0
0
azure_service_bus_async_batch_send_and_receive_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                # ServiceBusMessageBatch object reaches max_size.
33                # New ServiceBusMessageBatch object can be created here to send more data.
34                break
35        # Send the batch of messages to the queue
36        await sender.send_messages(batch_message)
37    print("Sent a batch of 10 messages")
38
39async def run():
40    # Create a Service Bus client
41    async with ServiceBusClient.from_connection_string(
42        conn_str=NAMESPACE_CONNECTION_STR,
43        logging_enable=True
44    ) as servicebus_client:
45        # Get a Queue Sender object to send messages to the queue
46        sender = servicebus_client.get_queue_sender(queue_name=QUEUE_NAME)
47        async with sender:
48            # Send messages
49            await send_single_message(sender)
50            await send_a_list_of_messages(sender)
51            await send_batch_message(sender)
52
53        # Get a Queue Receiver object to receive messages from the queue
54        receiver = servicebus_client.get_queue_receiver(queue_name=QUEUE_NAME, max_wait_time=5)
55        async with receiver:
56            async for msg in receiver:
57                print("Received: " + str(msg))
58                # Complete the message so that it is removed from the queue
59                await receiver.complete_message(msg)
60
61if __name__ == "__main__":
62    asyncio.run(run())