← Back to the chapter · Previous detail · Next detail →

Technical detail · AMQP Core: Consumers and Topology Contracts

Publish a marked factory alert

This Pika example assumes an open Pika channel object named channel, created from a BlockingConnection. Before running it, complete the alternate-exchange setup in “Test the alternate route honestly” below. Enable publisher confirms explicitly before publishing. mandatory=True requests unroutable-message return handling; it does not itself enable publisher confirms. A printed “Sent” line does not prove consumer processing.

import json
import time

channel.confirm_delivery()

def send_alert(severity, line, machine_id, message):
    """Send alert with proper routing key"""
    routing_key = f"alert.{severity}.line{line}.machine{machine_id:02d}"

    alert_data = {
        "timestamp": time.time(),
        "severity": severity,
        "line": line,
        "machine": machine_id,
        "message": message
    }

    # Publish with confirmation
    channel.basic_publish(
        exchange='factory-alerts',
        routing_key=routing_key,
        body=json.dumps(alert_data),
        properties=pika.BasicProperties(
            delivery_mode=2,  # Persistent
            content_type='application/json'
        ),
        mandatory=True  # Request return if no queue can be reached
    )
    print(f"Sent: {routing_key}")

# Examples
send_alert('critical', 1, 3, "Bearing temperature exceeded 95°C")
send_alert('warning', 2, 47, "Vibration threshold 80% reached")
send_alert('info', 4, 98, "Routine maintenance completed")

← Back to the chapter · Previous detail · Next detail →