rogashova_ekaterina_lab_4 #192
20
rogashova_ekaterina_lab_4/Consumer1.py
Normal file
20
rogashova_ekaterina_lab_4/Consumer1.py
Normal file
@ -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()
|
20
rogashova_ekaterina_lab_4/Consumer2.py
Normal file
20
rogashova_ekaterina_lab_4/Consumer2.py
Normal file
@ -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()
|
25
rogashova_ekaterina_lab_4/Publisher.py
Normal file
25
rogashova_ekaterina_lab_4/Publisher.py
Normal file
@ -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()
|
49
rogashova_ekaterina_lab_4/readme.md
Normal file
49
rogashova_ekaterina_lab_4/readme.md
Normal file
@ -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).
|
BIN
rogashova_ekaterina_lab_4/results/Consumer-1.jpg
Normal file
BIN
rogashova_ekaterina_lab_4/results/Consumer-1.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 81 KiB |
BIN
rogashova_ekaterina_lab_4/results/Consumer-3.jpg
Normal file
BIN
rogashova_ekaterina_lab_4/results/Consumer-3.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 87 KiB |
BIN
rogashova_ekaterina_lab_4/results/task1.jpg
Normal file
BIN
rogashova_ekaterina_lab_4/results/task1.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 84 KiB |
BIN
rogashova_ekaterina_lab_4/results/task2.jpg
Normal file
BIN
rogashova_ekaterina_lab_4/results/task2.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 129 KiB |
BIN
rogashova_ekaterina_lab_4/results/task3.jpg
Normal file
BIN
rogashova_ekaterina_lab_4/results/task3.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 67 KiB |
27
rogashova_ekaterina_lab_4/tasks/1/receive.py
Normal file
27
rogashova_ekaterina_lab_4/tasks/1/receive.py
Normal file
@ -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)
|
13
rogashova_ekaterina_lab_4/tasks/1/send.py
Normal file
13
rogashova_ekaterina_lab_4/tasks/1/send.py
Normal file
@ -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()
|
19
rogashova_ekaterina_lab_4/tasks/2/new_task.py
Normal file
19
rogashova_ekaterina_lab_4/tasks/2/new_task.py
Normal file
@ -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()
|
22
rogashova_ekaterina_lab_4/tasks/2/worker.py
Normal file
22
rogashova_ekaterina_lab_4/tasks/2/worker.py
Normal file
@ -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()
|
13
rogashova_ekaterina_lab_4/tasks/3/emit_log.py
Normal file
13
rogashova_ekaterina_lab_4/tasks/3/emit_log.py
Normal file
@ -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()
|
22
rogashova_ekaterina_lab_4/tasks/3/receive_logs.py
Normal file
22
rogashova_ekaterina_lab_4/tasks/3/receive_logs.py
Normal file
@ -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()
|
Loading…
Reference in New Issue
Block a user