Files
learning-rabbitmq/producer.py
2026-04-14 21:54:58 +00:00

42 lines
1.3 KiB
Python

import pika
import time
import json
conn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
ch = conn.channel()
# can redeclare qs, but since they are in main no need to
# the op would've been idempotent if I did though
# random objets to be conv to json
orders = [
{"order_id": 1001, "user_id": "u1", "amount": 49.99,
"should_fail": False, "retry_count": 0},
{"order_id": 1002, "user_id": "u2", "amount": 19.50,
"should_fail": False, "retry_count": 0},
{"order_id": 1003, "user_id": "u3", "amount": 99.00,
"should_fail": True, "retry_count": 0},
{"order_id": 1004, "user_id": "u4", "amount": 10.00,
"should_fail": False, "retry_count": 0},
{"order_id": 1005, "user_id": "u5", "amount": 75.25,
"should_fail": False, "retry_count": 0},
]
while True:
for order in orders:
time.sleep(1)
body = json.dumps(order)
ch.basic_publish(
exchange="orders.x",
routing_key="order.created", # as in the bindings
body=body,
properties=pika.BasicProperties(
delivery_mode=2, # persistent msg, committed to disk before ack
content_type="application/json"
)
)
print(f"published order {order['order_id']}")
conn.close()