DAS_2024_1/yakovleva_yulia_lab_4/Consumer1.py
2024-10-21 14:31:58 +04:00

44 lines
1.4 KiB
Python

import pika
import random
import time
from datetime import datetime
queue_name = 'queue1'
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}] Потребитель 1: сообщение - '{message}'")
# Имитация обработки сообщения
time.sleep(random.choice([1, 2]))
print(f"[{received_time}] Потребитель 1: сообщение '{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("Соединение закрыто.")