Using Celery with existing RabbitMQ messages

…衆ロ難τιáo~ 提交于 2019-12-02 21:07:23

It's currently hard to add custom consumers to the celery workers, but this is changing in the development version (to become 3.1) where I've added support for Consumer boot-steps.

There's no documentation yet as I've just finished implementing it, but here's an example:

from celery import Celery
from celery.bin import Option
from celery.bootsteps import ConsumerStep
from kombu import Consumer, Exchange, Queue

class CustomConsumer(ConsumerStep):
   queue = Queue('custom', Exchange('custom'), routing_key='custom')

   def __init__(self, c, enable_custom_consumer=False, **kwargs):
       self.enable = self.enable_custom_consumer

   def get_consumers(self, connection):
       return [
           Consumer(connection.channel(),
               queues=[self.queue],
               callbacks=[self.on_message]),
       ]

   def on_message(self, body, message):
       print('GOT MESSAGE: %r' % (body, ))
       message.ack()


celery = Celery(broker='amqp://localhost//')
celery.steps['consumer'].add(CustomConsumer)
celery.user_options['worker'].add(
    Option('--enable-custom-consumer', action='store_true',
           help='Enable our custom consumer.'),
)

Note that the API may change in the final version, one thing that I'm not yet sure about is how channels are handled after get_consumer(connection). Currently the channel of the consumer is closed when connection is lost, and at shutdown, but people may want to handle channels manually. In that case there's always the possibility of customizing ConsumerStep, or writing a new StartStopStep.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!