Azure Service Bus, sending messages to topics using Python SDK

367 views Asked by At

I have this snippet in a code that is running on a Function App:

from azure.servicebus import ServiceBusClient, ServiceBusMessage

client = ServiceBusClient.from_connection_string('<conn_string>')
sender = client.get_topic_sender('<topic>')
sender.send_messages(ServiceBusMessage('<message>', subject='<subject>'))

Each time I try to send a message after the function is idle for a few minutes, the function seems to take much longer. I'm not very familiar with the mechanism of how this works, but it seems that the client or topic sender is reconnecting.

How can I keep this sender alive so that it won't take such a long time?

1

There are 1 answers

0
Sampath On BEST ANSWER

Note: A message may be scheduled for delayed delivery using the ServiceBusSender.schedule_messages() method, or by specifying ServiceBusMessage.scheduled_enqueue_time_utc before calling ServiceBusSender.send_messages() The code below uses the Azure Service Bus client library for Python to send messages to Azure Service Bus topics reference.

  • The function is idle for a few minutes one possible solution is to set sender.renew_sender() every 10 minutes will ensure a continuous connection.
service_bus_client.renew_sender()
                time.sleep(600)

  • MyServiceBusClient class that connects to Azure Service Bus using a connection string and sends a message to a topic.
  • The send_message_to_topic() function sends a message to the topic using the sender object.
  • Create an Azure Service Bus and copy the Connection String.Code reference from MSDOC. For best implementation refer of Azure service Bus refer this MSDOC.

Code with send_messages():

from azure.servicebus import ServiceBusClient, ServiceBusMessage

class MyServiceBusClient:
    def __init__(self, conn_str, topic_name):
        self.conn_str = conn_str
        self.topic_name = topic_name
        self.client = None
        self.sender = None

    def connect(self):
        if not self.client:
            self.client = ServiceBusClient.from_connection_string(self.conn_str)
            self.sender = self.client.get_topic_sender(self.topic_name)

    def is_connected(self):
        return self.client is not None

    def send_message(self, message_body, subject=None):
        if not self.is_connected():
            raise Exception("Not connected to Azure Service Bus. Call connect() before sending messages.")

        sender = self.sender
        sender.send_messages(ServiceBusMessage(message_body, subject=subject))

    def close(self):
        if self.client:
            self.client.close()

def send_message_to_topic():
    # Initialize your Service Bus client
    service_bus_client = MyServiceBusClient('AzureServiceBusConn_String', 'AzureServiceBusTopic')

    try:
        # Connect to Azure Service Bus
        service_bus_client.connect()

        # Check if connected
        if service_bus_client.is_connected():
            # Send messages using the persistent sender
            service_bus_client.send_message('YourMessageBody', subject='YourSubject')
            print("Message sent successfully.")
        else:
            print("Failed to connect to Azure Service Bus.")

    except Exception as ex:
        print(f"An error occurred: {ex}")

    finally:
        # Close the client when done
        service_bus_client.close()

# Call the function to send a message to the topic
send_message_to_topic()

Output: enter image description here

Azure: enter image description here

  • For more detail on scheduling and schedule cancellation please see a sample here.

enter image description here

Scheduler a timer to execute the function periodically:

enter image description here