DAS_2024_1/yakovleva_yulia_lab_4/Consumer2.py

37 lines
1.2 KiB
Python
Raw Permalink Normal View History

2024-10-21 14:31:58 +04:00
import pika
from datetime import datetime
queue_name = 'queue2'
exchange = 'logs'
def callback(ch, method, properties, body):
received_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
message = body.decode()
print(f"[{received_time}] Потребитель 2: пришло сообщение '{message}'")
print(f"[{received_time}] Потребитель 2: сообщение '{message}' обработано\n")
ch.basic_ack(delivery_tag=method.delivery_tag)
def setup_connection():
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue=queue_name)
channel.queue_bind(exchange=exchange, queue=queue_name)
return connection, channel
if __name__ == '__main__':
connection, channel = setup_connection()
try:
print("[*] Ожидание сообщений")
channel.basic_consume(queue=queue_name, on_message_callback=callback)
channel.start_consuming()
except KeyboardInterrupt:
print("Остановка...")
finally:
if connection.is_open:
connection.close()
print("Соединение закрыто.")