PyRSMQ

Python Implementation of Redis Simple Message Queue Algorithm

RSMQ: Redis Simple Message Queue for Node.js

Build Status Coverage Status PyPI version

Redis Simple Message Queue

A lightweight message queue for Python that requires no dedicated queue server. Just a Redis server.

This is a Python implementation of https://github.com/smrchy/rsmq)

PyRSMQ Release Notes

Quick Intro to RSMQ

RSMQ is trying to emulate Amazon’s SQS-like functionality, where there is a named queue (name consists of “namespace” and “qname”) that is backed by Redis. Queue must be created before used. Once created, Producers will place messages in queue and Consumers will retrieve them. Messages have a property of “visibility” - where any “visible” message may be consumed, but “invisbile” messages stay in the queue until they become visible or deleted.

Once queue exists, a Producer can push messages into it. When pushing to queue, message gets a unique ID that is used to track the message. The ID can be used to delete message by Producer or Consumer or to control its “visibility”

During insertion, a message may have a delay associated with it. “Delay” will mark message “invisible” for specified delay duration, and thus prevent it from being consumed. Delay may be specified at time of message creation or, if not specified, default value set in queue attributes is used.

Consumer will retrieve next message in queue via either receiveMessage() or popMessage() command. If we do not care about reliability of the message beyond delivery, a good and simple way to retrieve it is via popMessage(). When using popMessage() the message is automatically deleted at the same time it is received.

However in many cases we want to ensure that the message is not only received, but is also processed before being deleted. For this, receiveMessage() is best. When using receiveMessage(), the message is kept in the queue, but is marked “invisible” for some amount of time. The amount of time is specified by queue attribute vt(visibility timeout), which may also be overridden by specifying a custom vt value in receiveMessage() call. When using receiveMessage(), Consumer’ is responsible for deleting the message before vt timeout occurs, otherwise the message may be picked up by another Consumer. Consumer can also extend the timeout if it needs more time, or clear the timeout if processing failed.

A “Realtime” mode can be specified when using the RSMQ queue. “Realtime” mode adds a Redis PUBSUB based notification that would allow Consumers to be notified whenever a new message is added to the queue. This can remove the need for Consumer to constantly poll the queue when it is empty (NOTE: as of this writing, “Realtime” is not yet implemented in python version)

Python Implementation Notes

NOTE This project is written for Python 3.x. While some attempts to get Python2 support were made I am not sure how stable it would be under Python 2

This version is heavily based on Java version (https://github.com/igr/jrsmq), which in turn is based on the original Node.JS version.

API

To start with, best effort is made to maintain same method/parameter/usablity named of both version (which, admittedly, resulted in a not very pythonic API)

Although much of the original API is still present, some alternatives are added to make life a bit easier.

For example, while you can set any available parameter to command using the “setter” method, you can also simply specify the parameters when creating the command. So these two commands do same thing:

rqsm.createQueue().qname("my-queue").vt(20).execute()

rqsm.createQueue(qname="my-queue", vt=20).execute()

In addition, when creating a main controller, any non-controller parameters specified will become defaults for all commands created via this controller - so, for example, you if you plan to work with only one queue using this controller, you can specify the qname parameter during creation of the controller and not need to specify it in every command.

A “Consumer” Service Utility

In addition to all the APIs in the original RSMQ project, a simple to use consumer implementation is included in this project as RedisSMQConsumer and RedisSMQConsumerThread classes.

RedisSMQConsumer

The RedisSMQConsumer instance wraps an RSMQ Controller and is configured with a processor method which is called every time a new message is received. The processor method returns true or false to indicate if message was successfully received and the message is deleted or returned to the queue based on that. The consumer auto-extends the visibility timeout as long as the processor is running, reducing the concern that item will become visible again if processing takes too long and visibility timeout elapses.

NOTE: Since currently the realtime functionality is not implemented, Consumer implementation is currently using polling to check for queue items.

Example usage:

from rsmq.consumer import RedisSMQConsumer

# define Processor
def processor(id, message, rc, ts):
  ''' process the message '''
  # Do something
  return True

# create consumer
consumer = RedisSMQConsumer('my-queue', processor, host='127.0.0.1')

# run consumer
consumer.run()

For a more complete example, see examples directory.

RedisSMQConsumerThread

RedisSMQConsumerThread is simply a version of RedisSMQConsumer that extends Thread class.

Once created you can start it like any other thread, or stop it using stop(wait) method, where wait specifies maximum time to wait for the thread to stop before returning (the thread would still be trying to stop if the wait time expires)

Note that the thread is by default set to be a daemon thread, so on exit of your main thread it will be stopped. If you wish to disable daemon flag, just disable it before starting the thread as with any other thread

Example usage:

from rsmq.consumer import RedisSMQConsumerThread

# define Processor
def processor(id, message, rc, ts):
  ''' process the message '''
  # Do something
  return True

# create consumer
consumer = RedisSMQConsumerThread('my-queue', processor, host='127.0.0.1')

# start consumer
consumer.start()

# do what else you need to, then stop the consumer
# (waiting for 10 seconds for it to stop):
consumer.stop(10)

For a more complete example, see examples directory.

General Usage Approach

As copied from other versions, the general approach is to create a controller object and use that object to create, configure and then execute commands

Error Handling

Commands follow the pattern of other versions and throw exceptions on error.

Exceptions are all extending RedisSMQException() and include:

However, if you do not wish to use exceptions, you can turn them off on per-command or per-controller basis by using .exceptions(False) on the relevant object. For example, the following will create Queue only if it does not exist without throwing an exception:

rsmq.createQueue().exceptions(False).execute()

Usage

Example Usage

In this example we will create a new queue named “my-queue”, deleting previous version, if one exists, and then send a message with a 2 second delay. We will then demonstrate both the lack of message before delay expires and getting the message after timeout

from pprint import pprint
import time

from rsmq import RedisSMQ


# Create controller.
# In this case we are specifying the host and default queue name
queue = RedisSMQ(host="127.0.0.1", qname="myqueue")


# Delete Queue if it already exists, ignoring exceptions
queue.deleteQueue().exceptions(False).execute()

# Create Queue with default visibility timeout of 20 and delay of 0
# demonstrating here both ways of setting parameters
queue.createQueue(delay=0).vt(20).execute()

# Send a message with a 2 second delay
message_id = queue.sendMessage(delay=2).message("Hello World").execute()

pprint({'queue_status': queue.getQueueAttributes().execute()})

# Try to get a message - this will not succeed, as our message has a delay and no other
# messages are in the queue
msg = queue.receiveMessage().exceptions(False).execute()

# Message should be False as we got no message
pprint({"Message": msg})

print("Waiting for our message to become visible")
# Wait for our message to become visible
time.sleep(2)

pprint({'queue_status': queue.getQueueAttributes().execute()})
# Get our message
msg = queue.receiveMessage().execute()

# Message should now be there
pprint({"Message": msg})

# Delete Message
queue.deleteMessage(id=msg['id'])

pprint({'queue_status': queue.getQueueAttributes().execute()})
# delete our queue
queue.deleteQueue().execute()

# No action
queue.quit()

RedisSMQ Controller API Usage

Usage: rsmq.rqsm.RedisSMQ([options])

Controller Methods

Controller Commands