← Back to the chapter · Next detail →
Technical detail · AMQP Operations: Deployment and Broker Health
Python publisher with Pika
import pika
import json
from typing import Dict, Any
class AMQPPublisher:
"""Production-ready AMQP publisher with reliability features."""
def __init__(self, host: str, exchange: str):
self.connection = pika.BlockingConnection(
pika.ConnectionParameters(
host=host,
heartbeat=600, # Detect dead connections
blocked_connection_timeout=300
)
)
self.channel = self.connection.channel()
self.exchange = exchange
# Enable publisher confirms
self.channel.confirm_delivery()
# Declare durable exchange
self.channel.exchange_declare(
exchange=exchange,
exchange_type='topic',
durable=True
)
def publish(self, routing_key: str, message: Dict[str, Any],
message_id: str = None) -> bool:
"""
Publish message with persistence and confirmation.
Args:
routing_key: Topic routing key (e.g., 'sensor.temperature.line1')
message: Dictionary to serialize as JSON
message_id: Unique ID for idempotency (optional)
Returns:
True if broker acknowledged, False otherwise
"""
properties = pika.BasicProperties(
delivery_mode=2, # Persistent
content_type='application/json',
message_id=message_id
)
try:
self.channel.basic_publish(
exchange=self.exchange,
routing_key=routing_key,
body=json.dumps(message),
properties=properties,
mandatory=True # Return if unroutable
)
return True
except pika.exceptions.UnroutableError:
print(f"Message unroutable: {routing_key}")
return False
def close(self):
"""Clean shutdown."""
self.connection.close()
# Usage example
publisher = AMQPPublisher('localhost', 'sensor-data')
publisher.publish(
routing_key='sensor.temperature.line1.machine3',
message={'temp': 75.3, 'timestamp': 1698765432},
message_id='msg-001'
)