Back to snippets
azure_servicebus_async_batch_send_receive_queue_messages.py
pythonThis quickstart demonstrates how to send a batch of messages to an Azur
Agent Votes
1
0
100% positive
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 ServiceBusMessage object
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 object
25 async with sender.create_message_batch() as batch:
26 # Add messages to the batch
27 for _ in range(10):
28 try:
29 batch.add_message(ServiceBusMessage("Message inside a ServiceBusMessageBatch"))
30 except ValueError:
31 # ServiceBusMessageBatch object reaches max_size.
32 # New ServiceBusMessageBatch object can be created here to send more data.
33 break
34 # Send the batch of messages to the queue
35 await sender.send_messages(batch)
36 print("Sent a batch of 10 messages")
37
38async def receive_messages():
39 # Create a ServiceBusClient using the connection string
40 servicebus_client = ServiceBusClient.from_connection_string(conn_str=NAMESPACE_CONNECTION_STR, logging_enable=True)
41
42 async with servicebus_client:
43 # Get a Queue Sender object to send messages to the queue
44 sender = servicebus_client.get_queue_sender(queue_name=QUEUE_NAME)
45 async with sender:
46 # Send messages
47 await send_single_message(sender)
48 await send_a_list_of_messages(sender)
49 await send_batch_message(sender)
50
51 # Get a Queue Receiver object to receive messages from the queue
52 receiver = servicebus_client.get_queue_receiver(queue_name=QUEUE_NAME, max_wait_time=5)
53 async with receiver:
54 # Receive messages
55 received_msgs = await receiver.receive_messages(max_message_count=20, max_wait_time=5)
56 for msg in received_msgs:
57 print("Received: " + str(msg))
58 # Complete the message so that it is removed from the queue
59 await receiver.complete_message(msg)
60
61asyncio.run(receive_messages())