forked from Alexey/DAS_2023_1
good start
This commit is contained in:
parent
60ff69f12d
commit
ca5364cb65
@ -16,20 +16,19 @@
|
|||||||
|
|
||||||
# Запуск
|
# Запуск
|
||||||
|
|
||||||
Командой в консоли проекта "docker-compose up -d"
|
Проект запускается в ide просто по нажатию у питон файла на функцию мейн.
|
||||||
|
Очередь сообщений запускается такой командой
|
||||||
|
docker run -it --rm --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3-management
|
||||||
|
|
||||||
# Описание работы:
|
# Описание работы:
|
||||||
Развернули два приложения
|
Развернули два приложения
|
||||||
Сервисы используем из предыдущей работы
|
Сервисы используем из предыдущей работы
|
||||||
Предметная область - врачи и пациенты
|
Предметная область - врачи и пациенты
|
||||||
|
|
||||||
1. Сервис с врачами:
|
1. Consumer 1 - врач 1:
|
||||||
- доступ на http://localhost:5000/
|
2. Consumer 2 - врач 2:
|
||||||
|
|
||||||
2. Сервис с пациентами:
|
Оба врача принимают пациентов.
|
||||||
- доступ на http://localhost:5001/
|
|
||||||
|
|
||||||
Сервисы связываются друг с другом через ссылку и библиотеку requests
|
|
||||||
|
|
||||||
Flask-приложение с RabbitMQ, использующего библиотеку pika для publisher и Celery для consumers.
|
Flask-приложение с RabbitMQ, использующего библиотеку pika для publisher и Celery для consumers.
|
||||||
Приложение Flask (app.py), издателя (publisher.py) и двух потребителей (consumer.py).
|
Приложение Flask (app.py), издателя (publisher.py) и двух потребителей (consumer.py).
|
||||||
|
@ -1,6 +0,0 @@
|
|||||||
version: "2.1"
|
|
||||||
services:
|
|
||||||
rabbitmq:
|
|
||||||
image: rabbitmq:3.10.7-management
|
|
||||||
ports:
|
|
||||||
- 15672:15672
|
|
@ -1,21 +0,0 @@
|
|||||||
from celery import Celery
|
|
||||||
from flask import Flask, render_template
|
|
||||||
|
|
||||||
app = Flask(__name__)
|
|
||||||
|
|
||||||
# Celery конфигурация
|
|
||||||
app.config['CELERY_BROKER_URL'] = 'pyamqp://guest:guest@localhost//'
|
|
||||||
app.config['CELERY_RESULT_BACKEND'] = 'rpc://'
|
|
||||||
|
|
||||||
# Создаем инстанс Celery
|
|
||||||
celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
|
|
||||||
celery.conf.update(app.config)
|
|
||||||
|
|
||||||
|
|
||||||
@app.route('/')
|
|
||||||
def index():
|
|
||||||
return render_template('index.html')
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
app.run(debug=True)
|
|
@ -1,33 +0,0 @@
|
|||||||
from celery import Celery
|
|
||||||
import time
|
|
||||||
import pika
|
|
||||||
|
|
||||||
app = Celery('consumer', broker='pyamqp://guest:guest@localhost//')
|
|
||||||
|
|
||||||
|
|
||||||
@app.task
|
|
||||||
def process_messages(queue_name, delay):
|
|
||||||
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
|
|
||||||
channel = connection.channel()
|
|
||||||
|
|
||||||
# Объявляем очередь с именем
|
|
||||||
channel.queue_declare(queue=queue_name)
|
|
||||||
|
|
||||||
# Привязываем очередь к 'logs' exchange
|
|
||||||
channel.queue_bind(exchange='logs', queue=queue_name)
|
|
||||||
|
|
||||||
def callback(ch, method, properties, body):
|
|
||||||
print(f" [x] Получено сообщение: {body}")
|
|
||||||
time.sleep(delay)
|
|
||||||
print(f" [x] Обработано сообщение: {body}")
|
|
||||||
|
|
||||||
# Устанавливаем consumer а чтобы получать сообщения из очереди
|
|
||||||
channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)
|
|
||||||
|
|
||||||
print(f' [*] Ожидаем сообщения от {queue_name}')
|
|
||||||
channel.start_consuming()
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
process_messages.delay('consumer1_queue', 2) # Queue для Consumer 1 с задержкой 2 с
|
|
||||||
process_messages.delay('consumer2_queue', 0) # Queue для Consumer 2 без задержки
|
|
@ -1,23 +0,0 @@
|
|||||||
import pika
|
|
||||||
import time
|
|
||||||
|
|
||||||
connection_params = pika.ConnectionParameters(
|
|
||||||
host='localhost', # RabbitMQ server hostname
|
|
||||||
port=15672, # RabbitMQ server port
|
|
||||||
credentials=pika.PlainCredentials('guest', 'guest') # credentials
|
|
||||||
)
|
|
||||||
|
|
||||||
connection = pika.BlockingConnection(connection_params)
|
|
||||||
channel = connection.channel()
|
|
||||||
|
|
||||||
# Объявляем exchange с именем 'logs' типа 'fanout'
|
|
||||||
channel.exchange_declare(exchange='logs', exchange_type='fanout')
|
|
||||||
|
|
||||||
# Отдаем сообщение в 'logs' exchange каждую секунду
|
|
||||||
while True:
|
|
||||||
message = "Пациент прибыл" # Сообщение
|
|
||||||
channel.basic_publish(exchange='logs', routing_key='', body=message)
|
|
||||||
print(f" [x] Отправлено сообщение: {message}")
|
|
||||||
time.sleep(1)
|
|
||||||
|
|
||||||
connection.close()
|
|
20
antonov_dmitry_lab4/rabbitmq/app.py
Normal file
20
antonov_dmitry_lab4/rabbitmq/app.py
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
from flask import Flask, render_template, request
|
||||||
|
from publisher import publish_message
|
||||||
|
|
||||||
|
app = Flask(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index():
|
||||||
|
return render_template('index.html')
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/publish', methods=['GET'])
|
||||||
|
def publish():
|
||||||
|
message = request.form['message']
|
||||||
|
publish_message(message)
|
||||||
|
return 'Пациент прибыл: {}'.format(message)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
app.run(debug=True)
|
25
antonov_dmitry_lab4/rabbitmq/consumer1.py
Normal file
25
antonov_dmitry_lab4/rabbitmq/consumer1.py
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
import pika
|
||||||
|
|
||||||
|
def callback(ch, method, properties, body):
|
||||||
|
print(" [x] Врач 1 принимает пациента '{}'".format(body.decode()))
|
||||||
|
|
||||||
|
def consume_messages():
|
||||||
|
connection = pika.BlockingConnection(pika.ConnectionParameters(
|
||||||
|
host='localhost', # RabbitMQ server hostname
|
||||||
|
port=5672, # RabbitMQ server port
|
||||||
|
credentials=pika.PlainCredentials('guest', 'guest') # credentials
|
||||||
|
))
|
||||||
|
channel = connection.channel()
|
||||||
|
channel.queue_declare(queue='example_queue')
|
||||||
|
channel.basic_consume(queue='example_queue', on_message_callback=callback, auto_ack=True)
|
||||||
|
print(' [*] Врач 1 ожидает приема')
|
||||||
|
try:
|
||||||
|
channel.start_consuming()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print('Прервано. Останавливаем прием...')
|
||||||
|
channel.stop_consuming()
|
||||||
|
connection.close()
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
consume_messages()
|
||||||
|
|
25
antonov_dmitry_lab4/rabbitmq/consumer2.py
Normal file
25
antonov_dmitry_lab4/rabbitmq/consumer2.py
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
import pika
|
||||||
|
|
||||||
|
def callback(ch, method, properties, body):
|
||||||
|
print(" [x] Врач 2 принимает пациента '{}'".format(body.decode()))
|
||||||
|
|
||||||
|
def consume_messages():
|
||||||
|
connection = pika.BlockingConnection(pika.ConnectionParameters(
|
||||||
|
host='localhost', # RabbitMQ server hostname
|
||||||
|
port=5672, # RabbitMQ server port
|
||||||
|
credentials=pika.PlainCredentials('guest', 'guest') # credentials
|
||||||
|
))
|
||||||
|
channel = connection.channel()
|
||||||
|
channel.queue_declare(queue='example_queue')
|
||||||
|
channel.basic_consume(queue='example_queue', on_message_callback=callback, auto_ack=True)
|
||||||
|
print(' Врач 2 ожидает пациента')
|
||||||
|
try:
|
||||||
|
channel.start_consuming()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print('Врач 2 прекращает прием')
|
||||||
|
channel.stop_consuming()
|
||||||
|
connection.close()
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
consume_messages()
|
||||||
|
|
20
antonov_dmitry_lab4/rabbitmq/publisher.py
Normal file
20
antonov_dmitry_lab4/rabbitmq/publisher.py
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
import pika
|
||||||
|
import time
|
||||||
|
|
||||||
|
def publish_message(message):
|
||||||
|
connection = pika.BlockingConnection(pika.ConnectionParameters(
|
||||||
|
host='localhost', # RabbitMQ server hostname
|
||||||
|
port=15672, # RabbitMQ server port
|
||||||
|
credentials=pika.PlainCredentials('guest', 'guest') # credentials
|
||||||
|
))
|
||||||
|
channel = connection.channel()
|
||||||
|
channel.queue_declare(queue='example_queue')
|
||||||
|
channel.basic_publish(exchange='', routing_key='example_queue', body=message)
|
||||||
|
# Отдаем сообщение в 'logs' exchange каждую секунду
|
||||||
|
while True:
|
||||||
|
message = "Пациент прибыл" # Сообщение
|
||||||
|
channel.basic_publish(exchange='logs', routing_key='', body=message)
|
||||||
|
print(f" [x] Отправлено сообщение: {message}")
|
||||||
|
time.sleep(1)
|
||||||
|
print(" [x] Отправлено '{}'".format(message))
|
||||||
|
connection.close()
|
BIN
antonov_dmitry_lab4/screens/img.png
Normal file
BIN
antonov_dmitry_lab4/screens/img.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 50 KiB |
BIN
antonov_dmitry_lab4/screens/img_1.png
Normal file
BIN
antonov_dmitry_lab4/screens/img_1.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 102 KiB |
BIN
antonov_dmitry_lab4/screens/img_2.png
Normal file
BIN
antonov_dmitry_lab4/screens/img_2.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 40 KiB |
Loading…
Reference in New Issue
Block a user