This document is for Kombu's development version, which can be significantly different from previous releases. Get the stable docs here: 5.0.

Consumers

Basics

The Consumer takes a connection (or channel) and a list of queues to consume from. Several consumers can be mixed to consume from different channels, as they all bind to the same connection, and drain_events will drain events from all channels on that connection.

Note

Kombu since 3.0 will only accept json/binary or text messages by default, to allow deserialization of other formats you have to specify them in the accept argument (in addition to setting the right content type for your messages):

>>> Consumer(conn, accept=['json', 'pickle', 'msgpack', 'yaml'])

You can create a consumer using a Connection. This consumer is consuming from a single queue with name ‘queue’:

>>> queue = Queue('queue', routing_key='queue')
>>> consumer = connection.Consumer(queue)

You can also instantiate Consumer directly, it takes a channel or a connection as an argument. This consumer also consumes from single queue with name ‘queue’:

>>> queue = Queue('queue', routing_key='queue')
>>> with Connection('amqp://') as conn:
...     with conn.channel() as channel:
...         consumer = Consumer(channel, queue)

A consumer needs to specify a handler for received data. This handler is specified in the form of a callback. The callback function is called by kombu every time a new message is received. The callback is called with two parameters: body, containing deserialized data sent by a producer, and a Message instance message. The user is responsible for acknowledging messages when manual acknowledgement is set.

>>> def callback(body, message):
...     print(body)
...     message.ack()

>>> consumer.register_callback(callback)

Draining events from a single consumer

The method drain_events blocks indefinitely by default. This example sets the timeout to 1 second:

>>> with consumer:
...     connection.drain_events(timeout=1)

Draining events from several consumers

Each consumer has its own list of queues. Each consumer accepts data in ‘json’ format:

>>> from kombu.utils.compat import nested

>>> queues1 = [Queue('queue11', routing_key='queue11'),
               Queue('queue12', routing_key='queue12')]
>>> queues2 = [Queue('queue21', routing_key='queue21'),
               Queue('queue22', routing_key='queue22')]
>>> with connection.channel(), connection.channel() as (channel1, channel2):
...     with nested(Consumer(channel1, queues1, accept=['json']),
...                 Consumer(channel2, queues2, accept=['json'])):
...         connection.drain_events(timeout=1)

The full example will look as follows:

from kombu import Connection, Consumer, Queue

def callback(body, message):
    print('RECEIVED MESSAGE: {0!r}'.format(body))
    message.ack()

queue1 = Queue('queue1', routing_key='queue1')
queue2 = Queue('queue2', routing_key='queue2')

with Connection('amqp://') as conn:
    with conn.channel() as channel:
        consumer = Consumer(conn, [queue1, queue2], accept=['json'])
        consumer.register_callback(callback)
        with consumer:
            conn.drain_events(timeout=1)

Consumer mixin classes

Kombu provides predefined mixin classes in module mixins. It contains two classes: ConsumerMixin for creating consumers and ConsumerProducerMixin for creating consumers supporting also publishing messages. Consumers can be created just by subclassing mixin class and overriding some of the methods:

from kombu.mixins import ConsumerMixin

class C(ConsumerMixin):

    def __init__(self, connection):
        self.connection = connection

    def get_consumers(self, Consumer, channel):
        return [
            Consumer(channel, callbacks=[self.on_message], accept=['json']),
        ]

    def on_message(self, body, message):
        print('RECEIVED MESSAGE: {0!r}'.format(body))
        message.ack()

C(connection).run()

and with multiple channels again:

from kombu import Consumer
from kombu.mixins import ConsumerMixin

class C(ConsumerMixin):
    channel2 = None

    def __init__(self, connection):
        self.connection = connection

    def get_consumers(self, _, default_channel):
        self.channel2 = default_channel.connection.channel()
        return [Consumer(default_channel, queues1,
                         callbacks=[self.on_message],
                         accept=['json']),
                Consumer(self.channel2, queues2,
                         callbacks=[self.on_special_message],
                         accept=['json'])]

    def on_consume_end(self, connection, default_channel):
        if self.channel2:
            self.channel2.close()

C(connection).run()

The main use of ConsumerProducerMixin is to create consumers that need to also publish messages on a separate connection (e.g. sending rpc replies, streaming results):

from kombu import Producer, Queue
from kombu.mixins import ConsumerProducerMixin

rpc_queue = Queue('rpc_queue')

class Worker(ConsumerProducerMixin):

    def __init__(self, connection):
        self.connection = connection

    def get_consumers(self, Consumer, channel):
        return [Consumer(
            queues=[rpc_queue],
            on_message=self.on_request,
            accept={'application/json'},
            prefetch_count=1,
        )]

    def on_request(self, message):
        n = message.payload['n']
        print(' [.] fib({0})'.format(n))
        result = fib(n)

        self.producer.publish(
            {'result': result},
            exchange='', routing_key=message.properties['reply_to'],
            correlation_id=message.properties['correlation_id'],
            serializer='json',
            retry=True,
        )
        message.ack()

See also

examples/rpc-tut6/ in the Github repository.

Advanced Topics

RabbitMQ

Consumer Priorities

RabbitMQ defines a consumer priority extension to the amqp protocol, that can be enabled by setting the x-priority argument to basic.consume.

In kombu you can specify this argument on the Queue, like this:

queue = Queue('name', Exchange('exchange_name', type='direct'),
              consumer_arguments={'x-priority': 10})

Read more about consumer priorities here: https://www.rabbitmq.com/consumer-priority.html

Reference

class kombu.Consumer(channel, queues=None, no_ack=None, auto_declare=None, callbacks=None, on_decode_error=None, on_message=None, accept=None, prefetch_count=None, tag_prefix=None)[source]

Message consumer.

Parameters
exception ContentDisallowed

Consumer does not allow this content-type.

accept = None

List of accepted content-types.

An exception will be raised if the consumer receives a message with an untrusted content type. By default all content-types are accepted, but not if kombu.disable_untrusted_serializers() was called, in which case only json is allowed.

add_queue(queue)[source]

Add a queue to the list of queues to consume from.

Note

This will not start consuming from the queue, for that you will have to call consume() after.

auto_declare = True

By default all entities will be declared at instantiation, if you want to handle this manually you can set this to False.

callbacks = None

List of callbacks called in order when a message is received.

The signature of the callbacks must take two arguments: (body, message), which is the decoded message body and the Message instance.

cancel()[source]

End all active queue consumers.

Note

This does not affect already delivered messages, but it does mean the server will not send any more messages for this consumer.

cancel_by_queue(queue)[source]

Cancel consumer by queue name.

channel = None

The connection/channel to use for this consumer.

close()

End all active queue consumers.

Note

This does not affect already delivered messages, but it does mean the server will not send any more messages for this consumer.

consume(no_ack=None)[source]

Start consuming messages.

Can be called multiple times, but note that while it will consume from new queues added since the last call, it will not cancel consuming from removed queues ( use cancel_by_queue()).

Parameters

no_ack (bool) – See no_ack.

consuming_from(queue)[source]

Return True if currently consuming from queue’.

declare()[source]

Declare queues, exchanges and bindings.

Note

This is done automatically at instantiation when auto_declare is set.

flow(active)[source]

Enable/disable flow from peer.

This is a simple flow-control mechanism that a peer can use to avoid overflowing its queues or otherwise finding itself receiving more messages than it can process.

The peer that receives a request to stop sending content will finish sending the current content (if any), and then wait until flow is reactivated.

no_ack = None

Flag for automatic message acknowledgment. If enabled the messages are automatically acknowledged by the broker. This can increase performance but means that you have no control of when the message is removed.

Disabled by default.

on_decode_error = None

Callback called when a message can’t be decoded.

The signature of the callback must take two arguments: (message, exc), which is the message that can’t be decoded and the exception that occurred while trying to decode it.

on_message = None

Optional function called whenever a message is received.

When defined this function will be called instead of the receive() method, and callbacks will be disabled.

So this can be used as an alternative to callbacks when you don’t want the body to be automatically decoded. Note that the message will still be decompressed if the message has the compression header set.

The signature of the callback must take a single argument, which is the Message object.

Also note that the message.body attribute, which is the raw contents of the message body, may in some cases be a read-only buffer object.

prefetch_count = None

Initial prefetch count

If set, the consumer will set the prefetch_count QoS value at startup. Can also be changed using qos().

purge()[source]

Purge messages from all queues.

Warning

This will delete all ready messages, there is no undo operation.

qos(prefetch_size=0, prefetch_count=0, apply_global=False)[source]

Specify quality of service.

The client can request that messages should be sent in advance so that when the client finishes processing a message, the following message is already held locally, rather than needing to be sent down the channel. Prefetching gives a performance improvement.

The prefetch window is Ignored if the no_ack option is set.

Parameters
  • prefetch_size (int) – Specify the prefetch window in octets. The server will send a message in advance if it is equal to or smaller in size than the available prefetch size (and also falls within other prefetch limits). May be set to zero, meaning “no specific limit”, although other prefetch limits may still apply.

  • prefetch_count (int) – Specify the prefetch window in terms of whole messages.

  • apply_global (bool) – Apply new settings globally on all channels.

property queues

A single Queue, or a list of queues to consume from.

receive(body, message)[source]

Method called when a message is received.

This dispatches to the registered callbacks.

Parameters
  • body (Any) – The decoded message body.

  • message (Message) – The message instance.

Raises

NotImplementedError – If no consumer callbacks have been registered.

recover(requeue=False)[source]

Redeliver unacknowledged messages.

Asks the broker to redeliver all unacknowledged messages on the specified channel.

Parameters

requeue (bool) – By default the messages will be redelivered to the original recipient. With requeue set to true, the server will attempt to requeue the message, potentially then delivering it to an alternative subscriber.

register_callback(callback)[source]

Register a new callback to be called when a message is received.

Note

The signature of the callback needs to accept two arguments: (body, message), which is the decoded message body and the Message instance.

revive(channel)[source]

Revive consumer after connection loss.