python - 如何用flask和docker部署rabbitmq?

标签 python docker flask rabbitmq microservices

我正在做一个应用程序,后面部分使用 Flask,前面部分使用 Angular,采用微服务架构。 对于部署,我使用的是 docker,现在的问题是服务之间的通信。我读过最好的选择 es rabbit-mqtt 但我没有找到任何教程。

我的时间很少,因为要完成我的学位,所以我需要一个教程来让我快速创建服务之间的通信。

flask 不安,我用manager创建API-CRUD。

提前致谢

最佳答案

这是我的做法:

  1. flask 服务器
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. worker
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. docker 文件
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 服务器通信。

关于python - 如何用flask和docker部署rabbitmq?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56110148/

相关文章:

docker - 如何更改 docker 网桥地址空间(子网)?

python - 控制 Flask 应用程序中的 URL 顺序

python - 如何在 webassets 中传递过滤器特定配置选项

python - 如何为 flask 中的外部库禁用 ExtDeprecationWarning

Python 导入没有 "from"

python - 如何使用isalpha函数去除特殊字符

jenkins - 如何在 jenkins 管道作业中运行 docker 命令

python - Bigquery - 通过 python 将新数据行插入到表中

python - 如何仅使用 Python 获取视频 flv 片段的所有 url?

php - Nginx Net::ERR_INCOMPLETE_CHUNKED_ENCODING 试图显示大 JSON