To continuously monitor an Azure Service Bus topic as a receiver on a Linux machine using Python, follow these steps:
1. Install Required Python Package
pip install azure-servicebus
2. Python Script for Continuous Message Reception
Save this as servicebus_receiver.py:
import os
import time
from azure.servicebus import ServiceBusClient, ServiceBusMessage
# Configuration (use environment variables for security)
CONNECTION_STR = os.getenv("AZURE_SERVICEBUS_CONNECTION_STRING")
TOPIC_NAME = "your-topic-name"
SUBSCRIPTION_NAME = "your-subscription-name"
def process_message(message: ServiceBusMessage):
try:
print(f"Received message: {message.body}")
# Add your processing logic here
# Mark message as completed (remove from queue)
message.complete()
except Exception as e:
print(f"Error processing message: {e}")
message.abandon() # Release the lock if processing fails
def receive_messages():
servicebus_client = ServiceBusClient.from_connection_string(conn_str=CONNECTION_STR)
with servicebus_client.get_subscription_receiver(topic_name=TOPIC_NAME, subscription_name=SUBSCRIPTION_NAME) as receiver:
while True:
try:
# Wait for messages (max 10 seconds)
received_msgs = receiver.receive_messages(max_message_count=10, max_wait_time=10)
if not received_msgs:
print("No messages received. Checking again...")
continue
for msg in received_msgs:
process_message(msg)
except Exception as e:
print(f"Receiver error: {e}")
time.sleep(5) # Wait before retrying
if __name__ == "__main__":
print("Starting Service Bus receiver...")
receive_messages()
3. Run the Script Securely
Set environment variables (do not hardcode credentials):
export AZURE_SERVICEBUS_CONNECTION_STRING="Endpoint=sb://<your-namespace>.servicebus.windows.net/;SharedAccessKeyName=<key-name>;SharedAccessKey=<key>"
Run the script in the background:
nohup python3 servicebus_receiver.py > servicebus_receiver.log 2>&1 &
4. Optional: Create a Systemd Service
For production stability, create a systemd service:
- Create a service file:
sudo nano /etc/systemd/system/servicebus-receiver.service
- Add this configuration:
[Unit]
Description=Azure Service Bus Receiver
After=network.target
[Service]
User=your-linux-user
WorkingDirectory=/path/to/script
ExecStart=/usr/bin/python3 /path/to/script/servicebus_receiver.py
Environment="AZURE_SERVICEBUS_CONNECTION_STRING=Endpoint=sb://<your-namespace>.servicebus.windows.net/;SharedAccessKeyName=<key-name>;SharedAccessKey=<key>"
Restart=always
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=servicebus-receiver
[Install]
WantedBy=multi-user.target
- Enable and start the service:
sudo systemctl daemon-reload
sudo systemctl enable servicebus-receiver
sudo systemctl start servicebus-receiver
Key Features
- Continuous Polling: Uses
receive_messages() in an infinite loop with a 10-second timeout.
- Error Handling: Gracefully handles processing errors and retries.
- Message Completion: Marks messages as complete after successful processing.
- Background Execution: Runs as a systemd service or background process.
Best Practices
- Lock Duration: Ensure message processing completes within the Service Bus lock duration (default 30s).
- Dead-Letter Queue: Add
message.dead_letter() logic for poison messages.
- Logging: Use structured logging (e.g.,
logging module) for production use.
- Security: Store secrets in Azure Key Vault or environment variables.
Let me know if you need help with message filtering or advanced features!