Examples

Once you have installed aiorsmq, you can test out some of its features.

Note: The examples in this page assume there is a Redis instance running at localhost:6379.

Sending Messages

In this example, we first create a connection to Redis by using the from_url function of the aioredis package. Then, we create a new queue called my-queue, and we send one message to it.

import asyncio  # For the .run() function
import aioredis  # For creating the connection to Redis
from aiorsmq import AIORSMQ


async def send_message():
    client = aioredis.from_url(url="redis://localhost:6379", decode_responses=True)
    rsmq = AIORSMQ(client=client)

    await rsmq.create_queue("my-queue")
    await rsmq.send_message("my-queue", "Hello, world!")


asyncio.run(send_message())

Receiving Messages

To receive a message, we need to call the receive_message method, like so:

import asyncio
import aioredis
from aiorsmq import AIORSMQ


async def receive_message():
    client = aioredis.from_url(url="redis://localhost:6379", decode_responses=True)
    rsmq = AIORSMQ(client=client)

    message = await rsmq.receive_message("my-queue")
    print("The message is:", message.contents)

    await rsmq.delete_message("my-queue", message.id)


asyncio.run(receive_message())

Running this code will print:

The message is: Hello, world!

Calling delete_message is necessary to ensure that the message is removed from the queue. By default, receiving a message from a queue will make the message ‘invisible’ for 30 seconds (this is called the visiblity timer or vt). After this period has elapsed, the message will be re-queued again. The idea of this mechanism is to ensure no messages are lost: if your program crashes or errors out after calling receive_message but before calling delete_message, you will have a chance to receive the message again.

If you wish to automatically delete a message immediately after receiving it, you can use the pop_message method instead.

Full Reference

To see the full documentation for every public class, method and function in aiorsmq, please see the API Documentation page.