52 lines
1.5 KiB
Python
52 lines
1.5 KiB
Python
import pika
|
|
import json
|
|
|
|
def main():
|
|
connection = pika.BlockingConnection(
|
|
pika.ConnectionParameters('localhost')
|
|
)
|
|
channel = connection.channel()
|
|
|
|
channel.exchange_declare(exchange='orders', exchange_type='fanout')
|
|
|
|
queue_name = 'order_processing_fast'
|
|
channel.queue_declare(queue=queue_name, durable=True)
|
|
|
|
channel.queue_bind(exchange='orders', queue=queue_name)
|
|
|
|
print(f' [*] Consumer 2 (FAST) started')
|
|
print(f' [*] Queue: {queue_name}')
|
|
print(f' [*] Processing time: instant')
|
|
print(' [*] Waiting for orders. To exit press CTRL+C')
|
|
|
|
def callback(ch, method, properties, body):
|
|
try:
|
|
order = json.loads(body.decode())
|
|
print(f" [x] Received order #{order['order_id']}: "
|
|
f"{order['product']} - ${order['amount']}")
|
|
|
|
print(f" [✓] Order #{order['order_id']} processed instantly")
|
|
|
|
ch.basic_ack(delivery_tag=method.delivery_tag)
|
|
|
|
except Exception as e:
|
|
print(f" [!] Error processing message: {e}")
|
|
ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True)
|
|
|
|
channel.basic_qos(prefetch_count=1)
|
|
|
|
channel.basic_consume(
|
|
queue=queue_name,
|
|
on_message_callback=callback
|
|
)
|
|
|
|
try:
|
|
channel.start_consuming()
|
|
except KeyboardInterrupt:
|
|
print('\n [*] Consumer 2 stopped')
|
|
finally:
|
|
connection.close()
|
|
|
|
if __name__ == '__main__':
|
|
main()
|