[Init] - Criando projeto de exemplo para demonstração do docker
This commit is contained in:
commit
01f86ca8fa
1
.env
Normal file
1
.env
Normal file
@ -0,0 +1 @@
|
|||||||
|
REGISTRY=gitea.adnangonzagaci.com
|
||||||
206
README.md
Normal file
206
README.md
Normal file
@ -0,0 +1,206 @@
|
|||||||
|
# Demonstração de Docker e Kubernetes
|
||||||
|
|
||||||
|
Um pequeno projeto de demonstração de docker e k8s, com um pouco de mensageria
|
||||||
|
|
||||||
|
## Project Overview
|
||||||
|
|
||||||
|
A demo é composta dos seguintes componentes
|
||||||
|
|
||||||
|
1. Um serviço **Produtor**(producer) que gera as tarefas e envia a fila de mensagens(rabbitmq)
|
||||||
|
2. Um serviço **Consumidor** que processa as tarefas a partir da fila de mensagens
|
||||||
|
3. **RabbitMQ** como um message broker
|
||||||
|
|
||||||
|
O ponto do projeto é mostrar:
|
||||||
|
- Como containerizar aplicações em python
|
||||||
|
- Como usar mensageria para distribuir carga
|
||||||
|
- Como containers podem se comunicar
|
||||||
|
- Como implantar e escalar serviços no kubernetes
|
||||||
|
|
||||||
|
## Estrutura de pastas
|
||||||
|
|
||||||
|
```
|
||||||
|
docker-k8s-demo/
|
||||||
|
├── producer/
|
||||||
|
│ ├── Dockerfile
|
||||||
|
│ ├── app.py
|
||||||
|
│ └── requirements.txt
|
||||||
|
├── consumer/
|
||||||
|
│ ├── Dockerfile
|
||||||
|
│ ├── app.py
|
||||||
|
│ └── requirements.txt
|
||||||
|
├── k8s/
|
||||||
|
│ ├── rabbitmq-deployment.yaml
|
||||||
|
│ ├── producer-deployment.yaml
|
||||||
|
│ └── consumer-deployment.yaml
|
||||||
|
└── docker-compose.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
## Executando o projeto
|
||||||
|
|
||||||
|
### Requisitos
|
||||||
|
|
||||||
|
- [Docker](https://docs.docker.com/get-docker/)
|
||||||
|
- [Docker Compose](https://docs.docker.com/compose/install/)
|
||||||
|
- Opcional: [k3s](https://k3s.io/)
|
||||||
|
- Opcional 2: [minikube](https://minikube.sigs.k8s.io/docs/start/?arch=%2Flinux%2Fx86-64%2Fstable%2Fbinary+download)
|
||||||
|
- Opcional 3 e Alternativa ao K8s: [Docker Swarn](https://docs.docker.com/engine/swarm/)
|
||||||
|
|
||||||
|
### Rodando com docker compose
|
||||||
|
|
||||||
|
1. Clone o repositório:
|
||||||
|
```
|
||||||
|
git clone gitea.adnangonzagaci.com/python-docker-sample.git
|
||||||
|
cd python-docker-sample
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Inicie os serviços:
|
||||||
|
```
|
||||||
|
docker-compose up
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Escale o consumidor de serviços:
|
||||||
|
```
|
||||||
|
docker-compose up -d --scale consumer=3
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Veja os logs:
|
||||||
|
```
|
||||||
|
docker-compose logs -f
|
||||||
|
```
|
||||||
|
|
||||||
|
5. Pare os serviços:
|
||||||
|
```
|
||||||
|
docker-compose down
|
||||||
|
```
|
||||||
|
|
||||||
|
### Construindo as imagens do docker manualmente
|
||||||
|
|
||||||
|
Se você quiser realizar o build das imagens manualmente:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Construa a imagem do produtor
|
||||||
|
cd producer
|
||||||
|
docker build -t demo/producer:latest .
|
||||||
|
|
||||||
|
# Construa a imagem do consumidor
|
||||||
|
cd ../consumer
|
||||||
|
docker build -t demo/consumer:latest .
|
||||||
|
```
|
||||||
|
|
||||||
|
## Introdução ao kubernetes
|
||||||
|
|
||||||
|
### Requisitos
|
||||||
|
|
||||||
|
- [kubectl](https://kubernetes.io/docs/tasks/tools/)
|
||||||
|
- A Kubernetes cluster (Minikube, kind, or cloud provider)
|
||||||
|
- Opcional: [k3s](https://k3s.io/)
|
||||||
|
- Opcional 2: [minikube](https://minikube.sigs.k8s.io/docs/start/?arch=%2Flinux%2Fx86-64%2Fstable%2Fbinary+download)
|
||||||
|
- Opcional 3 e Alternativa ao K8s: [Docker Swarn](https://docs.docker.com/engine/swarm/)
|
||||||
|
|
||||||
|
### Implantação/deploy no kubernetes
|
||||||
|
|
||||||
|
1. Atualize a imagem do manifesto yaml do k8s para apontar para o seu registro, ou pra sua nova imagem:
|
||||||
|
```bash
|
||||||
|
# Pode ser o Docker Hub, ou algum outro registro privado
|
||||||
|
sed -i 's|${REGISTRY}/producer:latest|nome_de_usuario/producer:latest|g' kubernetes/producer-deployment.yaml
|
||||||
|
sed -i 's|${REGISTRY}/consumer:latest|nome_de_usuario/consumer:latest|g' kubernetes/consumer-deployment.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Realize o upload das imagens docker ao registro:
|
||||||
|
```bash
|
||||||
|
docker push nome_de_usuario/producer:latest
|
||||||
|
docker push nome_de_usuario/consumer:latest
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Aplique os manifestos do kubernetes:
|
||||||
|
```bash
|
||||||
|
kubectl apply -f kubernetes/rabbitmq-deployment.yaml
|
||||||
|
kubectl apply -f kubernetes/producer-deployment.yaml
|
||||||
|
kubectl apply -f kubernetes/consumer-deployment.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Verifique os status dos pods:
|
||||||
|
```bash
|
||||||
|
kubectl get pods
|
||||||
|
```
|
||||||
|
|
||||||
|
5. Veja os logs de um pod especifico:
|
||||||
|
```bash
|
||||||
|
kubectl logs -f <nome-pod>
|
||||||
|
```
|
||||||
|
|
||||||
|
6. Escale o deploy do consumidor:
|
||||||
|
```bash
|
||||||
|
kubectl scale deployment consumer --replicas=4
|
||||||
|
```
|
||||||
|
|
||||||
|
## Funcionamento
|
||||||
|
|
||||||
|
1. **RabbitMQ** serve como um message broker rodando como um container.
|
||||||
|
2. O **Produtor**(producer) gera as tarefas e envia eles para o RabbitMQ a cada 5 segundos.
|
||||||
|
3. O **Consumidor**/es (consumer) processa as tarefas da fila.
|
||||||
|
4. Multiplos consumidores podem rodar em paralelo para distribuir a carga.
|
||||||
|
|
||||||
|
## Conceitos principais da demonstração
|
||||||
|
|
||||||
|
### Docker
|
||||||
|
- Criar um Dockerfile
|
||||||
|
- Construir imagens docker
|
||||||
|
- Rodar containers com variaveis de ambientes.
|
||||||
|
- Redes em containers
|
||||||
|
- orquestração de containers com Docker Compose
|
||||||
|
|
||||||
|
### Kubernetes
|
||||||
|
|
||||||
|
- Deployments
|
||||||
|
- Services
|
||||||
|
- Escalonamento
|
||||||
|
- Configuração de ambiente
|
||||||
|
- Comunicação entre serviços
|
||||||
|
|
||||||
|
### Mensageria
|
||||||
|
- Fila de mensagens (Message queues)
|
||||||
|
- Padrão Produtor/Consumidor (Producer/consumer pattern)
|
||||||
|
- Distribuição de carga
|
||||||
|
- Entrega de mensagens confiável.
|
||||||
|
|
||||||
|
## Bônus e Dever de casa:
|
||||||
|
|
||||||
|
Tente adaptar o projeto para utilizar alguma ferramenta de RPA, como o Playwright:
|
||||||
|
|
||||||
|
1. Adicione as bibliotecas necessárias no `requirements.txt`:
|
||||||
|
```
|
||||||
|
pika==1.3.2
|
||||||
|
playwright==1.34.0
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Atualize o Dockerfile incluir as dependências do navegador:
|
||||||
|
```Dockerfile
|
||||||
|
FROM python:alpine@sha256:18159b2be11db91f84b8f8f655cd860f805dbd9e49a583ddaac8ab39bf4fe1a7
|
||||||
|
|
||||||
|
RUN apt-get update && apt-get install -y \
|
||||||
|
wget \
|
||||||
|
gnupg \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY requirements.txt .
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
RUN playwright install --with-deps chromium
|
||||||
|
|
||||||
|
COPY app.py .
|
||||||
|
|
||||||
|
CMD ["python", "app.py"]
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Modifique o consumidor para realizar tarefas de RPA com o Playwright(bem, fica de dever de casa)
|
||||||
|
|
||||||
|
## Próximos passos:
|
||||||
|
|
||||||
|
1. Autenticação e segurança no RabbitMQ.
|
||||||
|
2. Implemente tratamento de erro e logica de retentativa.
|
||||||
|
3. Adicione monitoria e logging.
|
||||||
|
4. Crie ConfigMaps e Secrets, evite deixar tudo em comandos ou dados sensiveis em arquivos no git.
|
||||||
|
5. Deploy automatizado, não precisa ser nada exigente, arrisca num LLM da vida gerar uma action do github.
|
||||||
10
consumer/Dockerfile
Normal file
10
consumer/Dockerfile
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
FROM python:alpine@sha256:18159b2be11db91f84b8f8f655cd860f805dbd9e49a583ddaac8ab39bf4fe1a7
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY requirements.txt .
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
COPY app.py .
|
||||||
|
|
||||||
|
CMD ["python", "app.py"]
|
||||||
96
consumer/app.py
Normal file
96
consumer/app.py
Normal file
@ -0,0 +1,96 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
import pika
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
import os
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||||
|
)
|
||||||
|
logger = logging.getLogger("consumer")
|
||||||
|
|
||||||
|
RABBITMQ_HOST = os.getenv("RABBITMQ_HOST", "rabbitmq")
|
||||||
|
RABBITMQ_PORT = int(os.getenv("RABBITMQ_PORT", "5672"))
|
||||||
|
RABBITMQ_USER = os.getenv("RABBITMQ_USER", "guest")
|
||||||
|
RABBITMQ_PASS = os.getenv("RABBITMQ_PASS", "guest")
|
||||||
|
QUEUE_NAME = os.getenv("QUEUE_NAME", "task_queue")
|
||||||
|
|
||||||
|
|
||||||
|
def connect_to_rabbitmq():
|
||||||
|
"""Establish connection to RabbitMQ with retry logic"""
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
credentials = pika.PlainCredentials(RABBITMQ_USER, RABBITMQ_PASS)
|
||||||
|
connection = pika.BlockingConnection(
|
||||||
|
pika.ConnectionParameters(
|
||||||
|
host=RABBITMQ_HOST,
|
||||||
|
port=RABBITMQ_PORT,
|
||||||
|
credentials=credentials,
|
||||||
|
heartbeat=600,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
logger.info("Connected to RabbitMQ successfully")
|
||||||
|
return connection
|
||||||
|
except pika.exceptions.AMQPConnectionError:
|
||||||
|
logger.warning("Failed to connect to RabbitMQ. Retrying in 5 seconds...")
|
||||||
|
time.sleep(5)
|
||||||
|
|
||||||
|
|
||||||
|
def process_message(task):
|
||||||
|
"""Process the received message"""
|
||||||
|
|
||||||
|
logger.info(f"Processing task {task['task_id']}: {task['data']}")
|
||||||
|
processing_time = 2 # seconds
|
||||||
|
time.sleep(processing_time)
|
||||||
|
logger.info(f"Completed task {task['task_id']} in {processing_time} seconds")
|
||||||
|
|
||||||
|
|
||||||
|
def callback(ch, method, properties, body):
|
||||||
|
"""Callback function for message consumption"""
|
||||||
|
try:
|
||||||
|
task = json.loads(body)
|
||||||
|
logger.info(f"Received task {task['task_id']} from {task['timestamp']}")
|
||||||
|
|
||||||
|
# Process the message
|
||||||
|
process_message(task)
|
||||||
|
|
||||||
|
# Acknowledge the message (remove from queue)
|
||||||
|
ch.basic_ack(delivery_tag=method.delivery_tag)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error processing message: {e}")
|
||||||
|
# Reject the message and requeue
|
||||||
|
ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
"""Main function that consumes messages from the queue"""
|
||||||
|
# Connect to RabbitMQ
|
||||||
|
connection = connect_to_rabbitmq()
|
||||||
|
channel = connection.channel()
|
||||||
|
|
||||||
|
# Declare the queue (creates if doesn't exist)
|
||||||
|
channel.queue_declare(queue=QUEUE_NAME, durable=True)
|
||||||
|
|
||||||
|
# Fair dispatch - don't give more than one message to a worker at a time
|
||||||
|
channel.basic_qos(prefetch_count=1)
|
||||||
|
|
||||||
|
# Set up the consumer
|
||||||
|
channel.basic_consume(queue=QUEUE_NAME, on_message_callback=callback)
|
||||||
|
|
||||||
|
logger.info("Consumer ready, waiting for messages...")
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Start consuming messages
|
||||||
|
channel.start_consuming()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
logger.info("Consumer stopping due to keyboard interrupt")
|
||||||
|
channel.stop_consuming()
|
||||||
|
finally:
|
||||||
|
connection.close()
|
||||||
|
logger.info("Connection to RabbitMQ closed")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
logger.info("Consumer service starting...")
|
||||||
|
main()
|
||||||
1
consumer/requirements.txt
Normal file
1
consumer/requirements.txt
Normal file
@ -0,0 +1 @@
|
|||||||
|
pika==1.3.2
|
||||||
41
docker-compose.yml
Normal file
41
docker-compose.yml
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
version: "3"
|
||||||
|
|
||||||
|
services:
|
||||||
|
rabbitmq:
|
||||||
|
image: rabbitmq:3-management
|
||||||
|
ports:
|
||||||
|
- "5672:5672" # RabbitMQ default port
|
||||||
|
- "15672:15672" # RabbitMQ management interface
|
||||||
|
environment:
|
||||||
|
- RABBITMQ_DEFAULT_USER=guest
|
||||||
|
- RABBITMQ_DEFAULT_PASS=guest
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "rabbitmqctl", "status"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
|
producer:
|
||||||
|
build: ./producer
|
||||||
|
depends_on:
|
||||||
|
- rabbitmq
|
||||||
|
environment:
|
||||||
|
- RABBITMQ_HOST=rabbitmq
|
||||||
|
- RABBITMQ_PORT=5672
|
||||||
|
- RABBITMQ_USER=guest
|
||||||
|
- RABBITMQ_PASS=guest
|
||||||
|
- QUEUE_NAME=task_queue
|
||||||
|
|
||||||
|
consumer:
|
||||||
|
build: ./consumer
|
||||||
|
depends_on:
|
||||||
|
- rabbitmq
|
||||||
|
environment:
|
||||||
|
- RABBITMQ_HOST=rabbitmq
|
||||||
|
- RABBITMQ_PORT=5672
|
||||||
|
- RABBITMQ_USER=guest
|
||||||
|
- RABBITMQ_PASS=guest
|
||||||
|
- QUEUE_NAME=task_queue
|
||||||
|
# Scale to multiple instances to demonstrate workload distribution
|
||||||
|
deploy:
|
||||||
|
replicas: 2
|
||||||
35
k8s/consumer-deployment.yaml
Normal file
35
k8s/consumer-deployment.yaml
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
apiVersion: apps/v1
|
||||||
|
kind: Deployment
|
||||||
|
metadata:
|
||||||
|
name: consumer
|
||||||
|
spec:
|
||||||
|
replicas: 2
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
app: consumer
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
labels:
|
||||||
|
app: consumer
|
||||||
|
spec:
|
||||||
|
containers:
|
||||||
|
- name: consumer
|
||||||
|
image: ${REGISTRY}/consumer:latest
|
||||||
|
env:
|
||||||
|
- name: RABBITMQ_HOST
|
||||||
|
value: "rabbitmq"
|
||||||
|
- name: RABBITMQ_PORT
|
||||||
|
value: "5672"
|
||||||
|
- name: RABBITMQ_USER
|
||||||
|
value: "guest"
|
||||||
|
- name: RABBITMQ_PASS
|
||||||
|
value: "guest"
|
||||||
|
- name: QUEUE_NAME
|
||||||
|
value: "task_queue"
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
cpu: 100m
|
||||||
|
memory: 128Mi
|
||||||
|
limits:
|
||||||
|
cpu: 200m
|
||||||
|
memory: 256Mi
|
||||||
35
k8s/producer-deployment.yaml
Normal file
35
k8s/producer-deployment.yaml
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
apiVersion: apps/v1
|
||||||
|
kind: Deployment
|
||||||
|
metadata:
|
||||||
|
name: producer
|
||||||
|
spec:
|
||||||
|
replicas: 1
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
app: producer
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
labels:
|
||||||
|
app: producer
|
||||||
|
spec:
|
||||||
|
containers:
|
||||||
|
- name: producer
|
||||||
|
image: ${REGISTRY}/producer:latest
|
||||||
|
env:
|
||||||
|
- name: RABBITMQ_HOST
|
||||||
|
value: "rabbitmq"
|
||||||
|
- name: RABBITMQ_PORT
|
||||||
|
value: "5672"
|
||||||
|
- name: RABBITMQ_USER
|
||||||
|
value: "guest"
|
||||||
|
- name: RABBITMQ_PASS
|
||||||
|
value: "guest"
|
||||||
|
- name: QUEUE_NAME
|
||||||
|
value: "task_queue"
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
cpu: 100m
|
||||||
|
memory: 128Mi
|
||||||
|
limits:
|
||||||
|
cpu: 200m
|
||||||
|
memory: 256Mi
|
||||||
48
k8s/rabbitmq-deployment.yaml
Normal file
48
k8s/rabbitmq-deployment.yaml
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
apiVersion: v1
|
||||||
|
kind: Service
|
||||||
|
metadata:
|
||||||
|
name: rabbitmq
|
||||||
|
labels:
|
||||||
|
app: rabbitmq
|
||||||
|
spec:
|
||||||
|
ports:
|
||||||
|
- port: 5672
|
||||||
|
name: rabbitmq
|
||||||
|
- port: 15672
|
||||||
|
name: management
|
||||||
|
selector:
|
||||||
|
app: rabbitmq
|
||||||
|
---
|
||||||
|
apiVersion: apps/v1
|
||||||
|
kind: Deployment
|
||||||
|
metadata:
|
||||||
|
name: rabbitmq
|
||||||
|
spec:
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
app: rabbitmq
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
labels:
|
||||||
|
app: rabbitmq
|
||||||
|
spec:
|
||||||
|
containers:
|
||||||
|
- name: rabbitmq
|
||||||
|
image: rabbitmq:3-management
|
||||||
|
ports:
|
||||||
|
- containerPort: 5672
|
||||||
|
name: rabbitmq
|
||||||
|
- containerPort: 15672
|
||||||
|
name: management
|
||||||
|
env:
|
||||||
|
- name: RABBITMQ_DEFAULT_USER
|
||||||
|
value: "guest"
|
||||||
|
- name: RABBITMQ_DEFAULT_PASS
|
||||||
|
value: "guest"
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
cpu: 100m
|
||||||
|
memory: 256Mi
|
||||||
|
limits:
|
||||||
|
cpu: 200m
|
||||||
|
memory: 512Mi
|
||||||
10
producer/Dockerfile
Normal file
10
producer/Dockerfile
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
FROM python:3.9-slim
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY requirements.txt .
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
COPY app.py .
|
||||||
|
|
||||||
|
CMD ["python", "app.py"]
|
||||||
90
producer/app.py
Normal file
90
producer/app.py
Normal file
@ -0,0 +1,90 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
import pika
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
import os
|
||||||
|
import logging
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
# Configure logging
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||||
|
)
|
||||||
|
logger = logging.getLogger("producer")
|
||||||
|
|
||||||
|
# RabbitMQ connection parameters
|
||||||
|
RABBITMQ_HOST = os.getenv("RABBITMQ_HOST", "rabbitmq")
|
||||||
|
RABBITMQ_PORT = int(os.getenv("RABBITMQ_PORT", "5672"))
|
||||||
|
RABBITMQ_USER = os.getenv("RABBITMQ_USER", "guest")
|
||||||
|
RABBITMQ_PASS = os.getenv("RABBITMQ_PASS", "guest")
|
||||||
|
QUEUE_NAME = os.getenv("QUEUE_NAME", "task_queue")
|
||||||
|
|
||||||
|
|
||||||
|
def connect_to_rabbitmq():
|
||||||
|
"""Establish connection to RabbitMQ with retry logic"""
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
credentials = pika.PlainCredentials(RABBITMQ_USER, RABBITMQ_PASS)
|
||||||
|
connection = pika.BlockingConnection(
|
||||||
|
pika.ConnectionParameters(
|
||||||
|
host=RABBITMQ_HOST,
|
||||||
|
port=RABBITMQ_PORT,
|
||||||
|
credentials=credentials,
|
||||||
|
heartbeat=600,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
logger.info("Connected to RabbitMQ successfully")
|
||||||
|
return connection
|
||||||
|
except pika.exceptions.AMQPConnectionError:
|
||||||
|
logger.warning("Failed to connect to RabbitMQ. Retrying in 5 seconds...")
|
||||||
|
time.sleep(5)
|
||||||
|
|
||||||
|
|
||||||
|
def publish_message(channel, task_id, task_data):
|
||||||
|
"""Publish a message to the queue"""
|
||||||
|
message = {
|
||||||
|
"task_id": task_id,
|
||||||
|
"timestamp": datetime.now().isoformat(),
|
||||||
|
"data": task_data,
|
||||||
|
}
|
||||||
|
|
||||||
|
channel.basic_publish(
|
||||||
|
exchange="",
|
||||||
|
routing_key=QUEUE_NAME,
|
||||||
|
body=json.dumps(message),
|
||||||
|
properties=pika.BasicProperties(
|
||||||
|
delivery_mode=2, # make message persistent
|
||||||
|
),
|
||||||
|
)
|
||||||
|
logger.info(f"Sent task {task_id}")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
"""Main function that sends a message every few seconds"""
|
||||||
|
connection = connect_to_rabbitmq()
|
||||||
|
channel = connection.channel()
|
||||||
|
|
||||||
|
# Declare a queue (creates if doesn't exist)
|
||||||
|
channel.queue_declare(queue=QUEUE_NAME, durable=True)
|
||||||
|
|
||||||
|
task_id = 0
|
||||||
|
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
task_id += 1
|
||||||
|
task_data = f"Task data for task {task_id}"
|
||||||
|
|
||||||
|
publish_message(channel, task_id, task_data)
|
||||||
|
|
||||||
|
# Wait before sending the next message
|
||||||
|
time.sleep(5)
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
logger.info("Producer stopping due to keyboard interrupt")
|
||||||
|
finally:
|
||||||
|
connection.close()
|
||||||
|
logger.info("Connection to RabbitMQ closed")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
logger.info("Producer service starting...")
|
||||||
|
main()
|
||||||
1
producer/requirements.txt
Normal file
1
producer/requirements.txt
Normal file
@ -0,0 +1 @@
|
|||||||
|
pika==1.3.2
|
||||||
Loading…
Reference in New Issue
Block a user