Continuously receiving messages from Azure ServiceBus
Asked Answered
S

1

7

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.

Subaquatic answered 19/1, 2021 at 18:36 Comment(5)
Not really. Saying “you can use WebJobs” is pretty open ended. how, “precisely”? Yes, I am looking for some handholding @singhh-msftSubaquatic
Cool, check out this step by step approach by Peter Pan: #57830672 on "Running Python script from Azure WebJob".Leathery
Does the above link help you further?Leathery
Does it help you?Leathery
@JohnLexus did u manage to complete this? What approach did u choose?Lenardlenci
L
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

Leathery answered 20/1, 2021 at 9:53 Comment(1)
For those stumbling upon this, note that the code does not fully answer the question. 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.Steve

© 2022 - 2024 — McMap. All rights reserved.