AMQP usage examples

AMQP queues and exchanges - receiving messages through channels and sending them with self.outgoing.amqp.

Receiving messages from queues

No programming is needed to receive messages from AMQP queues. Create an AMQP definition and channel in Dashboard, point it to a queue, and a service of your choice will be invoked for each message taken off the queue.

The message payload will be available in self.request.payload.

from zato.server.service import Service

class MyService(Service):

    def handle(self):

        # The AMQP message payload
        data = self.request.payload

        # Log what was received
        self.logger.info('AMQP message: %s', data)

Sending messages to exchanges

Create an AMQP definition and outgoing connection in Dashboard and use self.outgoing.amqp.send to publish messages.

from zato.server.service import Service

class MyService(Service):

    def handle(self):
        self.outgoing.amqp.send('Hello from Zato', 'my-outconn', '/exchange', 'routing-key')

Sending with headers

AMQP headers can be attached to each message by passing a headers dict.

from zato.server.service import Service

class MyService(Service):

    def handle(self):
        self.outgoing.amqp.send(
            'My message',
            'my-outconn',
            '/exchange',
            'routing-key',
            headers={'content-type': 'application/json', 'x-source': 'zato'},
        )

Processing and forwarding

A common pattern is to consume a message from one queue, process it and publish the result to another.

from zato.server.service import Service

class MyService(Service):

    def handle(self):

        # Incoming message from an AMQP channel
        data = self.request.payload
        self.logger.info('Processing: %s', data)

        # Forward to another exchange
        self.outgoing.amqp.send(data, 'processed-outconn', '/processed', 'done')

Learn more