6

According to the Azure ServiceBus docs here:

The ServiceBusReceiver class defines a high level interface for receiving messages from the Azure Service Bus Queue or Topic Subscription. The two primary channels for message receipt are receive() to make a single request for messages, and async for message in receiver: to continuously receive incoming messages in an ongoing fashion.

I have been attempting to use the async for message in receiver: advice to trigger a function everytime a message comes up, but I'm unsure how to do it right, as I have little experience working with async functions. Could someone familiar with async/service bus explain how the code should be formatted?

Edit: Let me provide some more context. I am creating a python flask service, and on start-up, I need it to start listening to messages on a topic/subscription_name. Whenever it receives a message, it will execute some code, then send a message back. So... how do I start an async listener on startup, and have it execute some code whenever it is triggered? It should also be able to process each message in a non-blocking way. So if two messages are received at once, both should be processed at the same time.

Note: I cannot use Azure Functions.

John Lexus
  • 3,576
  • 3
  • 15
  • 33

1 Answers1

2

Assuming you are using topic-subscription, you can use below code:

#!/usr/bin/env python

# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------

"""
Example to show receiving batch messages from a Service Bus Subscription under specific Topic asynchronously.
"""

# pylint: disable=C0111

import os
import asyncio
from azure.servicebus.aio import ServiceBusClient

CONNECTION_STR = os.environ['SERVICE_BUS_CONNECTION_STR']
TOPIC_NAME = os.environ["SERVICE_BUS_TOPIC_NAME"]
SUBSCRIPTION_NAME = os.environ["SERVICE_BUS_SUBSCRIPTION_NAME"]


async def main():
    servicebus_client = ServiceBusClient.from_connection_string(conn_str=CONNECTION_STR)

    async with servicebus_client:
        receiver = servicebus_client.get_subscription_receiver(
            topic_name=TOPIC_NAME,
            subscription_name=SUBSCRIPTION_NAME
        )
        async with receiver:
            received_msgs = await receiver.receive_messages(max_message_count=10, max_wait_time=5)
            for msg in received_msgs:
                print(str(msg))
                await receiver.complete_message(msg)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

Complete tutorial: Send messages to an Azure Service Bus topic and receive messages from subscriptions to the topic (Python)

Further, you can explore these samples (both sync and async versions): Azure Service Bus client library for Python Samples

Harshita Singh
  • 4,590
  • 1
  • 10
  • 13
  • 9
    For those stumbling upon this, note that the code does not fully answer the question. [receive-messages](https://learn.microsoft.com/en-us/python/api/azure-servicebus/azure.servicebus.servicebusreceiver?view=azure-python#azure-servicebus-servicebusreceiver-receive-messages) receives a batch of messages and returns whilst @John Lexus was requesting "advice to trigger a function everytime a message comes up". This won't work after the first batch is received. – Klaymen Jul 10 '22 at 08:29