From 83528356a1c301a9e951c8175d574794bd161777 Mon Sep 17 00:00:00 2001 From: acidmikk Date: Fri, 24 Nov 2023 07:55:12 +0400 Subject: [PATCH] worked nginx --- basharin_sevastyan_lab_3/docker-compose.yaml | 32 +++++++--- basharin_sevastyan_lab_3/nginx/nginx.conf | 30 +++++---- .../order_service/Dockerfile | 4 +- .../order_service/order_service.py | 10 +-- .../order_service/requirements.txt | 3 +- .../user_service/Dockerfile | 4 +- .../user_service/requirements.txt | 3 +- .../user_service/user_service.py | 64 +++++++++++-------- 8 files changed, 93 insertions(+), 57 deletions(-) diff --git a/basharin_sevastyan_lab_3/docker-compose.yaml b/basharin_sevastyan_lab_3/docker-compose.yaml index 104c23e..9a3d771 100644 --- a/basharin_sevastyan_lab_3/docker-compose.yaml +++ b/basharin_sevastyan_lab_3/docker-compose.yaml @@ -1,6 +1,15 @@ -version: '3' +version: '3.8' services: + rabbitmq: + image: "rabbitmq:management" + ports: + - "5672:5672" + - "15672:15672" + networks: + - my_network + restart: always + user-service: build: context: ./user_service @@ -8,6 +17,8 @@ services: - "5001:5001" depends_on: - rabbitmq + networks: + - my_network order-service: build: @@ -16,18 +27,21 @@ services: - "5002:5002" depends_on: - rabbitmq - - rabbitmq: - image: "rabbitmq:management" - ports: - - "5672:5672" - - "15672:15672" + networks: + - my_network nginx: - build: - context: ./nginx + image: nginx:latest ports: - "80:80" depends_on: - user-service - order-service + networks: + - my_network + volumes: + - ./nginx/nginx.conf:/etc/nginx/nginx.conf + +networks: + my_network: + driver: bridge \ No newline at end of file diff --git a/basharin_sevastyan_lab_3/nginx/nginx.conf b/basharin_sevastyan_lab_3/nginx/nginx.conf index 2f4ae77..9bb0979 100644 --- a/basharin_sevastyan_lab_3/nginx/nginx.conf +++ b/basharin_sevastyan_lab_3/nginx/nginx.conf @@ -1,19 +1,27 @@ -worker_processes 1; - events { worker_connections 1024; } http { - include /etc/nginx/mime.types; - default_type application/octet-stream; + server { + listen 80; + listen [::]:80; + server_name localhost; - sendfile on; - tcp_nopush on; - tcp_nodelay on; - keepalive_timeout 65; - types_hash_max_size 2048; + location /user-service/ { + proxy_pass http://user-service:5001/; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } - include /etc/nginx/conf.d/*.conf; - include /etc/nginx/sites-enabled/*; + location /order-service/ { + proxy_pass http://order-service:5002/; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + } } \ No newline at end of file diff --git a/basharin_sevastyan_lab_3/order_service/Dockerfile b/basharin_sevastyan_lab_3/order_service/Dockerfile index 46d249e..3e8508e 100644 --- a/basharin_sevastyan_lab_3/order_service/Dockerfile +++ b/basharin_sevastyan_lab_3/order_service/Dockerfile @@ -2,5 +2,5 @@ FROM python:3.11 WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt -COPY . . -CMD ["python", "order_service.py"] \ No newline at end of file +COPY . /app +CMD ["gunicorn", "--bind", "0.0.0.0:5002", "order_service:app"] \ No newline at end of file diff --git a/basharin_sevastyan_lab_3/order_service/order_service.py b/basharin_sevastyan_lab_3/order_service/order_service.py index 376e354..9d7c1c4 100644 --- a/basharin_sevastyan_lab_3/order_service/order_service.py +++ b/basharin_sevastyan_lab_3/order_service/order_service.py @@ -2,17 +2,17 @@ from flask import Flask, request, jsonify import pika import json +import time app = Flask(__name__) # Конфигурация RabbitMQ -connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) +time.sleep(20) +connection = pika.BlockingConnection(pika.ConnectionParameters('rabbitmq')) channel = connection.channel() -channel.exchange_declare(exchange='microservices', exchange_type='direct') +channel.queue_declare(queue='order_queue', durable=True) -# CRUD операции для заказов в order_service оставим здесь, чтобы он мог отправлять сообщения - # CREATE @app.route('/orders', methods=['POST']) def create_order(): @@ -22,7 +22,7 @@ def create_order(): # Отправка сообщения о создании заказа channel.basic_publish(exchange='microservices', routing_key='order', body=json.dumps(order)) - return jsonify(order), 201 + return order, 201 # READ diff --git a/basharin_sevastyan_lab_3/order_service/requirements.txt b/basharin_sevastyan_lab_3/order_service/requirements.txt index 920c2a7..e949d43 100644 --- a/basharin_sevastyan_lab_3/order_service/requirements.txt +++ b/basharin_sevastyan_lab_3/order_service/requirements.txt @@ -1,2 +1,3 @@ Flask==3.0.0 -pika==1.3.2 \ No newline at end of file +pika==1.3.2 +gunicorn==21.2.0 \ No newline at end of file diff --git a/basharin_sevastyan_lab_3/user_service/Dockerfile b/basharin_sevastyan_lab_3/user_service/Dockerfile index 467cb44..f868a6a 100644 --- a/basharin_sevastyan_lab_3/user_service/Dockerfile +++ b/basharin_sevastyan_lab_3/user_service/Dockerfile @@ -2,5 +2,5 @@ FROM python:3.11 WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt -COPY . . -CMD ["python", "user_service.py"] \ No newline at end of file +COPY . /app +CMD ["gunicorn", "--bind", "0.0.0.0:5001", "user_service:app"] \ No newline at end of file diff --git a/basharin_sevastyan_lab_3/user_service/requirements.txt b/basharin_sevastyan_lab_3/user_service/requirements.txt index 920c2a7..e949d43 100644 --- a/basharin_sevastyan_lab_3/user_service/requirements.txt +++ b/basharin_sevastyan_lab_3/user_service/requirements.txt @@ -1,2 +1,3 @@ Flask==3.0.0 -pika==1.3.2 \ No newline at end of file +pika==1.3.2 +gunicorn==21.2.0 \ No newline at end of file diff --git a/basharin_sevastyan_lab_3/user_service/user_service.py b/basharin_sevastyan_lab_3/user_service/user_service.py index cd6e450..a73ba14 100644 --- a/basharin_sevastyan_lab_3/user_service/user_service.py +++ b/basharin_sevastyan_lab_3/user_service/user_service.py @@ -1,16 +1,30 @@ # user_service.py +import time from flask import Flask, request, jsonify import pika import json +import threading app = Flask(__name__) +users = [] + # Конфигурация RabbitMQ -connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) -channel = connection.channel() -channel.exchange_declare(exchange='microservices', exchange_type='direct') - -users = [] +def connect_to_rabbitmq(): + retries = 5 + while retries > 0: + try: + connection = pika.BlockingConnection(pika.ConnectionParameters('rabbitmq')) + channel = connection.channel() + channel.queue_declare(queue='order_service', durable=True) + #channel.queue_bind(queue='order_service', routing_key='order') + channel.basic_consume(queue='order_service', on_message_callback=process_order_message, auto_ack=True) + print('Waiting for messages. To exit press CTRL+C') + channel.start_consuming() + except pika.exceptions.AMQPConnectionError: + print("Failed to connect to RabbitMQ. Retrying...") + retries -= 1 + time.sleep(5) # Обработка сообщений о заказах @@ -54,23 +68,19 @@ def process_order_message(ch, method, properties, body): print(f"User not found for order deletion: {user_id}") -# Начало прослушивания сообщений о заказах -channel.queue_declare(queue='order_service', durable=True) -channel.queue_bind(exchange='microservices', queue='order_service', routing_key='order') -channel.basic_consume(queue='order_service', on_message_callback=process_order_message, auto_ack=True) - -print('User service is waiting for order messages. To exit press CTRL+C') -channel.start_consuming() - - # CRUD операции для пользователей # CREATE -@app.route('/users', methods=['POST']) -def create_user(): - data = request.get_json() - user = {'id': len(users) + 1, 'name': data['name']} - users.append(user) - return jsonify(user), 201 +@app.route('/users', methods=['GET']) +def show_users(): + return users + + +@app.route('/add_users/', methods=['POST']) +def create_user(name): + if request.method == 'POST': + user = {'id': len(users) + 1, 'name': name} + users.append(user) + return jsonify(user) # READ @@ -80,19 +90,18 @@ def get_user(user_id): if user: return jsonify(user) else: - return jsonify({'error': 'User not found'}), 404 + return jsonify({'error': 'User not found'}) # UPDATE -@app.route('/users/', methods=['PUT']) -def update_user(user_id): +@app.route('/users/_', methods=['PUT']) +def update_user(user_id, name): user = next((user for user in users if user['id'] == user_id), None) if user: - data = request.get_json() - user['name'] = data['name'] + user['name'] = name return jsonify(user) else: - return jsonify({'error': 'User not found'}), 404 + return jsonify({'error': 'User not found'}) # DELETE @@ -104,4 +113,7 @@ def delete_user(user_id): if __name__ == '__main__': + # Запускаем обработчик RabbitMQ в отдельном потоке + rabbitmq_thread = threading.Thread(target=connect_to_rabbitmq()) + rabbitmq_thread.start() app.run(port=5001)