收听RabbitMQ并在同一服务器上运行flask

问题描述 投票:0回答:1

我有这样的Flask应用程序

from flask import Flask
from flask_restful import Resource, Api
from mq_handler import MessageBroker
import pika

app = Flask(__name__)
api = Api(app)
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
mb = MessageBroker(connection)



class HelloWorld(Resource):
    def get(self):
        mb.run()
        return {'hello': 'world'}


class LogHandler(Resource):
    def get(self, table):
        return {'TableName': table}




api.add_resource(HelloWorld, '/')
api.add_resource(LogHandler, '/log/<string:table>')



if __name__ == '__main__':
    app.run(debug=True)

我添加了MessageBroker类来处理我的所有RabbitMq消息

import pika
import json


class MessageBroker:
    def __init__(self, connection):
        self.connection = connection
        self.channel = connection.channel()

    def run(self):
        self.channel.start_consuming()
        self.channel.basic_consume(queue='logs',
                              auto_ack=True,
                              on_message_callback=self.handle_log)
        self.channel.start_consuming()

    def handle_log(self, ch, method, properties, body):
        decoded_content = body.decode('utf-8')
        json_payload = json.loads(decoded_content)
        print(" [x] Received %r" % json_payload['message'])

我尝试了不同的解决方案,但是可以让这两种服务在同一服务器上同时运行吗?有人可以解释一下吗?

通常..如何在烧瓶服务器上运行多个服务来监听?

python flask rabbitmq
1个回答
0
投票

我不确定要在端点上运行使用者是个好主意。因为,当您启动使用者时,它将运行IO循环以连续地从服务器获取和处理消息。除非从外部完成循环或消息处理中导致连接关闭的任何异常,否则循环不会退出。您能否说明在终端运行消费者的方案?

© www.soinside.com 2019 - 2024. All rights reserved.