我正在使用 Quart 框架,但我还需要使用 RabbitMQ Pika 连接器,但我无法让它们玩得很好,因为它们都有无限循环。
入口点:
from quart import Quart
from .service import Service
app = Quart(__name__)
@app.before_serving
async def startup():
app.service_task = asyncio.ensure_future(service.start())
if not service.initialise():
sys.exit()
服务等级:
class Service:
def __init__(self, new_instance):
self._connection = None
self._channel = None
self._messaging_thread = None
def initialise(self):
credentials = pika.PlainCredentials('username', 'password')
parameters = pika.ConnectionParameters('localhost', credentials=credentials)
self._connection = pika.BlockingConnection(parameters)
self._channel = self._connection.channel()
self._channel.queue_declare(queue='to_be_processed_queue')
self._channel.basic_consume(queue='to_be_processed_queue',
auto_ack=True,
on_message_callback=self.callback)
print('creating thread')
self._messaging_thread = Thread(target=self.run_consume())
#self._messaging_thread.start()
print('Thread created...')
def run_consume(self):
try:
self._channel.start_consuming()
except KeyboardInterrupt:
self._shutdown()
代码甚至没有到达print('Thread created...')我不明白。从这个问题我明白 RabbitMQ 不是线程安全的,但我不明白如何运行 RabbitMQ。