diff --git a/rogashova_ekaterina_lab_4/Consumer1.py b/rogashova_ekaterina_lab_4/Consumer1.py new file mode 100644 index 0000000..eec878c --- /dev/null +++ b/rogashova_ekaterina_lab_4/Consumer1.py @@ -0,0 +1,20 @@ +import pika +import json +import time + +connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) +channel = connection.channel() + +channel.queue_declare(queue='order_processing_queue') + +channel.queue_bind(exchange='online_store_events', queue='order_processing_queue') + +def callback(ch, method, properties, body): + message = json.loads(body.decode('utf-8')) + print(f"Received message in order_processing_queue: {message}") + time.sleep(2) + +channel.basic_consume(queue='order_processing_queue', on_message_callback=callback, auto_ack=True) + +print(' [*] Waiting for messages. To exit press CTRL+C') +channel.start_consuming() \ No newline at end of file diff --git a/rogashova_ekaterina_lab_4/Consumer2.py b/rogashova_ekaterina_lab_4/Consumer2.py new file mode 100644 index 0000000..66b7751 --- /dev/null +++ b/rogashova_ekaterina_lab_4/Consumer2.py @@ -0,0 +1,20 @@ +import pika +import json +import time + +connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) +channel = connection.channel() + +channel.queue_declare(queue='product_recommendation_queue') + +channel.queue_bind(exchange='online_store_events', queue='product_recommendation_queue') + +def callback(ch, method, properties, body): + message = json.loads(body) + print(f"Received message in product_recommendation_queue: {message}") + print(f"Обработка рекомендации: {message}") + +channel.basic_consume(queue='product_recommendation_queue', on_message_callback=callback, auto_ack=True) + +print(' [*] Waiting for messages. To exit press CTRL+C') +channel.start_consuming() \ No newline at end of file diff --git a/rogashova_ekaterina_lab_4/Publisher.py b/rogashova_ekaterina_lab_4/Publisher.py new file mode 100644 index 0000000..ecf390e --- /dev/null +++ b/rogashova_ekaterina_lab_4/Publisher.py @@ -0,0 +1,25 @@ +import pika +import json +import time +import random + +def generate_event(): + events = [ + {"event": "order_placed", "order_id": random.randint(100, 999), "product_name": random.choice(["iPhone 14 Pro", "Samsung Galaxy S23 Ultra", "MacBook Pro"]), "customer_id": random.randint(1000, 9999)}, + {"event": "product_viewed", "product_id": random.randint(1000, 9999), "product_name": random.choice(["iPhone 14 Pro", "Samsung Galaxy S23 Ultra", "MacBook Pro"])}, + {"event": "user_registered", "user_id": random.randint(10000, 99999), "username": f"user_{random.randint(1, 100)}"} + ] + return json.dumps(random.choice(events)) + +connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) +channel = connection.channel() + +channel.exchange_declare(exchange='online_store_events', exchange_type='fanout') + +while True: + message = generate_event() + channel.basic_publish(exchange='online_store_events', routing_key='', body=message) + print(f"Sent message: {message}") + time.sleep(1) + +connection.close() \ No newline at end of file diff --git a/rogashova_ekaterina_lab_4/readme.md b/rogashova_ekaterina_lab_4/readme.md new file mode 100644 index 0000000..a0aae9c --- /dev/null +++ b/rogashova_ekaterina_lab_4/readme.md @@ -0,0 +1,49 @@ +# Лабораторная работа №4 + +## Описание +Задание 1 из туториала: ![task1.jpg](results/task1.jpg) +Задание 2 из туториала: ![task2.jpg](results/task2.jpg) +Задание 3 из туториала: ![task3.jpg](results/task3.jpg) + +Также были созданы файлы Consumer1, Consumer2 и Publisher для обработки событий в сфере онлайн-магазина + +Publisher: + +• Создает обменник типа fanout с именем online_store_events. + +• Каждую секунду генерирует сообщения в формате JSON, описывающие различные события в магазине. + +• Отправляет сообщения в обменник. + +Consumer 1: + +• Создает очередь с именем order_processing_queue. + +• Создает привязку к обменнику online_store_events. + +• Принимает сообщения из очереди. + +• Обрабатывает сообщения, симулируя обработку заказа (использует time.sleep(2)). + +• Выводит в консоль информацию о полученном сообщении. + +Consumer 2: + +• Создает очередь с именем product_recommendation_queue. + +• Создает привязку к обменнику online_store_events. + +• Принимает сообщения из очереди. + +• Обрабатывает сообщения мгновенно, симулируя создание рекомендаций (использует print(f"Обработка рекомендации: {message}")). + +• Выводит в консоль информацию о полученном сообщении. + +## Вывод работы +Для того, чтобы сделать вывод, необходимо подождать некоторое время, тогда можно будет увидеть, что количество сообщений в order_processing_queue будет больше, +чем в product_recommendation_queue, так как во второй очереди происходит мгновенная обработка сообщений. +Если запустить несколько Consumer-1, то количество сообщений в order_processing_queue снизится, так как несколько экземпляров первого consumer будут работать параллельно, и RabbitMQ будет распределять входящие сообщения между ними (это называется "разделение нагрузки"). +![Consumer-1.jpg](results/Consumer-1.jpg) +![Consumer-3.jpg](results/Consumer-3.jpg) +## Видео +Работоспособность представлена на [видео](https://vk.com/video204968285_456240928). \ No newline at end of file diff --git a/rogashova_ekaterina_lab_4/results/Consumer-1.jpg b/rogashova_ekaterina_lab_4/results/Consumer-1.jpg new file mode 100644 index 0000000..82aee74 Binary files /dev/null and b/rogashova_ekaterina_lab_4/results/Consumer-1.jpg differ diff --git a/rogashova_ekaterina_lab_4/results/Consumer-3.jpg b/rogashova_ekaterina_lab_4/results/Consumer-3.jpg new file mode 100644 index 0000000..b4bccd1 Binary files /dev/null and b/rogashova_ekaterina_lab_4/results/Consumer-3.jpg differ diff --git a/rogashova_ekaterina_lab_4/results/task1.jpg b/rogashova_ekaterina_lab_4/results/task1.jpg new file mode 100644 index 0000000..61cb68e Binary files /dev/null and b/rogashova_ekaterina_lab_4/results/task1.jpg differ diff --git a/rogashova_ekaterina_lab_4/results/task2.jpg b/rogashova_ekaterina_lab_4/results/task2.jpg new file mode 100644 index 0000000..5dc9f80 Binary files /dev/null and b/rogashova_ekaterina_lab_4/results/task2.jpg differ diff --git a/rogashova_ekaterina_lab_4/results/task3.jpg b/rogashova_ekaterina_lab_4/results/task3.jpg new file mode 100644 index 0000000..34ae09e Binary files /dev/null and b/rogashova_ekaterina_lab_4/results/task3.jpg differ diff --git a/rogashova_ekaterina_lab_4/tasks/1/receive.py b/rogashova_ekaterina_lab_4/tasks/1/receive.py new file mode 100644 index 0000000..caf3912 --- /dev/null +++ b/rogashova_ekaterina_lab_4/tasks/1/receive.py @@ -0,0 +1,27 @@ +import pika, sys, os + +def main(): + connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) + channel = connection.channel() + + channel.queue_declare(queue='hello') + + def callback(ch, method, properties, body): + print(f" [x] Received {body}") + + channel.basic_consume(queue='hello', + auto_ack=True, + on_message_callback=callback) + + print(' [*] Waiting for messages. To exit press CTRL+C') + channel.start_consuming() + +if __name__ == '__main__': + try: + main() + except KeyboardInterrupt: + print('Interrupted') + try: + sys.exit(0) + except SystemExit: + os._exit(0) \ No newline at end of file diff --git a/rogashova_ekaterina_lab_4/tasks/1/send.py b/rogashova_ekaterina_lab_4/tasks/1/send.py new file mode 100644 index 0000000..21fb9c2 --- /dev/null +++ b/rogashova_ekaterina_lab_4/tasks/1/send.py @@ -0,0 +1,13 @@ +import pika + +connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) +channel = connection.channel() + +channel.queue_declare(queue='hello') + +channel.basic_publish(exchange='', + routing_key='hello', + body='Hello World!') +print(" [x] Sent 'Hello World!'") + +connection.close() \ No newline at end of file diff --git a/rogashova_ekaterina_lab_4/tasks/2/new_task.py b/rogashova_ekaterina_lab_4/tasks/2/new_task.py new file mode 100644 index 0000000..2e05d40 --- /dev/null +++ b/rogashova_ekaterina_lab_4/tasks/2/new_task.py @@ -0,0 +1,19 @@ +import pika +import sys + +connection = pika.BlockingConnection( + pika.ConnectionParameters(host='localhost')) +channel = connection.channel() + +channel.queue_declare(queue='task_queue', durable=True) + +message = ' '.join(sys.argv[1:]) or "Hello World!" +channel.basic_publish( + exchange='', + routing_key='task_queue', + body=message, + properties=pika.BasicProperties( + delivery_mode=pika.DeliveryMode.Persistent + )) +print(f" [x] Sent {message}") +connection.close() diff --git a/rogashova_ekaterina_lab_4/tasks/2/worker.py b/rogashova_ekaterina_lab_4/tasks/2/worker.py new file mode 100644 index 0000000..8f8ab64 --- /dev/null +++ b/rogashova_ekaterina_lab_4/tasks/2/worker.py @@ -0,0 +1,22 @@ +import pika +import time + +connection = pika.BlockingConnection( + pika.ConnectionParameters(host='localhost')) +channel = connection.channel() + +channel.queue_declare(queue='task_queue', durable=True) +print(' [*] Waiting for messages. To exit press CTRL+C') + + +def callback(ch, method, properties, body): + print(f" [x] Received {body.decode()}") + time.sleep(body.count(b'.')) + print(" [x] Done") + ch.basic_ack(delivery_tag=method.delivery_tag) + + +channel.basic_qos(prefetch_count=1) +channel.basic_consume(queue='task_queue', on_message_callback=callback) + +channel.start_consuming() \ No newline at end of file diff --git a/rogashova_ekaterina_lab_4/tasks/3/emit_log.py b/rogashova_ekaterina_lab_4/tasks/3/emit_log.py new file mode 100644 index 0000000..45b6989 --- /dev/null +++ b/rogashova_ekaterina_lab_4/tasks/3/emit_log.py @@ -0,0 +1,13 @@ +import pika +import sys + +connection = pika.BlockingConnection( + pika.ConnectionParameters(host='localhost')) +channel = connection.channel() + +channel.exchange_declare(exchange='logs', exchange_type='fanout') + +message = ' '.join(sys.argv[1:]) or "info: Hello World!" +channel.basic_publish(exchange='logs', routing_key='', body=message) +print(f" [x] Sent {message}") +connection.close() \ No newline at end of file diff --git a/rogashova_ekaterina_lab_4/tasks/3/receive_logs.py b/rogashova_ekaterina_lab_4/tasks/3/receive_logs.py new file mode 100644 index 0000000..60d881d --- /dev/null +++ b/rogashova_ekaterina_lab_4/tasks/3/receive_logs.py @@ -0,0 +1,22 @@ +import pika + +connection = pika.BlockingConnection( + pika.ConnectionParameters(host='localhost')) +channel = connection.channel() + +channel.exchange_declare(exchange='logs', exchange_type='fanout') + +result = channel.queue_declare(queue='', exclusive=True) +queue_name = result.method.queue + +channel.queue_bind(exchange='logs', queue=queue_name) + +print(' [*] Waiting for logs. To exit press CTRL+C') + +def callback(ch, method, properties, body): + print(f" [x] {body}") + +channel.basic_consume( + queue=queue_name, on_message_callback=callback, auto_ack=True) + +channel.start_consuming() \ No newline at end of file