如何使用Flask和Docker部署Rabbitmq?

时间:2019-05-13 10:07:55

标签: python docker flask rabbitmq microservices

我正在做一个带有微服务体系结构的应用程序,该应用程序的后部为烧瓶,前部为角形。 对于部署,我使用的是docker,现在的问题是服务之间的通信。我读过最好的选择es rabbit-mqtt,但是我没有找到任何教程。

我几乎没有时间,因为这是为了完成我的学位,所以我需要一个教程,可以让我快速创建服务之间的交流。

烧瓶不安,我使用管理器创建API-CRUD。

预先感谢

3 个答案:

答案 0 :(得分:1)

这是我的做法:

  1. 烧瓶服务器
from flask import Flask
import pika
import uuid
import threading

app = Flask(__name__)
queue = {}


class FibonacciRpcClient(object):

    def __init__(self):
        self.connection = pika.BlockingConnection(
            pika.ConnectionParameters(host='rabbit'))

        self.channel = self.connection.channel()

        result = self.channel.queue_declare('', exclusive=True)
        self.callback_queue = result.method.queue

        self.channel.basic_consume(
            queue=self.callback_queue,
            on_message_callback=self.on_response,
            auto_ack=True)

    def on_response(self, ch, method, props, body):
        if self.corr_id == props.correlation_id:
            self.response = body

    def call(self, n):
        self.response = None
        self.corr_id = str(uuid.uuid4())
        queue[self.corr_id] = None
        self.channel.basic_publish(
            exchange='',
            routing_key='rpc_queue',
            properties=pika.BasicProperties(
                reply_to=self.callback_queue,
                correlation_id=self.corr_id,
            ),
            body=str(n))
        while self.response is None:
            self.connection.process_data_events()
        queue[self.corr_id] = self.response
        print(self.response)
        return int(self.response)


@app.route("/calculate/<payload>")
def calculate(payload):
    n = int(payload)
    fibonacci_rpc = FibonacciRpcClient()
    threading.Thread(target=fibonacci_rpc.call, args=(n,)).start()
    return "sent " + payload


@app.route("/results")
def send_results():
    return str(queue.items())

  1. 工人
import pika

connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='localhost'))

channel = connection.channel()

channel.queue_declare(queue='rpc_queue')


def fib(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fib(n - 1) + fib(n - 2)


def on_request(ch, method, props, body):
    n = int(body)
    print(" [.] fib(%s)" % n)
    response = fib(n)
    print(" [.] calculated (%s)" % response)

    ch.basic_publish(exchange='',
                     routing_key=props.reply_to,
                     properties=pika.BasicProperties(correlation_id=props.correlation_id),
                     body=str(response))
    ch.basic_ack(delivery_tag=method.delivery_tag)


channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue='rpc_queue', on_message_callback=on_request)

print(" [x] Awaiting RPC requests")
channel.start_consuming()

以上两个是基于RPC上的RabbitMQ教程的。

  1. Dockerfile
FROM python:3
RUN mkdir code
ADD flask_server.py requirements.txt /code/
WORKDIR /code
RUN pip install -r requirements.txt
ENV FLASK_APP flask_server.py
EXPOSE 5000
CMD ["flask", "run", "-h", "0.0.0.0"]
  1. Docker-compose.yml
services:
    web:
        build: .
        ports:
            - "5000:5000"
        links: rabbit
        volumes:
            - .:/code
    rabbit:
        hostname: rabbit
        image: rabbitmq:latest
        ports:
            - "5672:5672"

运行docker-compose up,Flask服务器应开始与RabbitMQ服务器通信。

答案 1 :(得分:1)

有许多方法可以编写RabbitMQ服务器,工作程序和Dockerfile。
第一个答案显示了很好的例子。

我只强调当工作人员(在您的情况下为 web 服务)尝试访问它时,RabbitMQ服务器可能未准备就绪< / strong>。
为此,我建议像这样写docker-compose.yml文件

version: "3"

services:

  web:
    build: .
    ports:
      - "5000:5000"
    restart: on-failure
    depends_on:
      - rabbitmq
    volumes:
      - .:/code

  rabbit:
    image: rabbitmq:latest
    expose:
      - 5672
    healthcheck:
      test: [ "CMD", "nc", "-z", "localhost", "5672" ]
      interval: 3s
      timeout: 10s
      retries: 3

那么,我在这里做什么?

1)我已经在 web 服务中添加了depends_onrestart属性,并在 rabbit中添加了healthcheck属性服务。
现在 web 服务将自行重启,直到 rabbit 服务运行正常。

2)在兔子服务中,我使用expose属性而不是ports,因为在您的情况下5672端口需要在容器之间共享,并且不需要需要暴露给主机。

来自Expose文档:

暴露端口而不将其发布到主机上-它们将 仅可通过链接服务访问。只有内部端口可以 指定。

3)我删除了links属性,因为(取自here):

不需要链接即可使服务进行通信-默认情况下, 任何服务都可以使用该服务的名称到达其他任何服务。

答案 2 :(得分:0)

https://youtu.be/ZxVpsClqjdw 这些视频用代码解释了一切

,并且具有docker-compose

version: '3'

services:  

  redis:
    image: redis:latest
    hostname: redis

  rabbit:
    hostname: rabbit
    image: rabbitmq:latest
    environment:
      - RABBITMQ_DEFAULT_USER=admin
      - RABBITMQ_DEFAULT_PASS=mypass

  web:
    build:
      context: .
      dockerfile: Dockerfile
    hostname: web
    command: ./scripts/run_web.sh
    volumes:
      - .:/app 
    ports:
      - "5000:5000"
    links:
      - rabbit
      - redis

  worker:
    build:
      context: .
      dockerfile: Dockerfile
    command: ./scripts/run_celery.sh
    volumes:
      - .:/app
    links:
      - rabbit
      - redis
    depends_on:
      - rabbit

并使用连接

BROKER_URL = 'amqp://admin:mypass@rabbit//'
CELERY = Celery('tasks',backend=REDIS_URL,broker=BROKER_URL)

进一步的解释https://medium.com/swlh/dockerized-flask-celery-rabbitmq-redis-application-f317825a03b