PyIMQ: Python bindings to OpenMQ¶
This documentation is a work-in-progress, and will be updated frequently
pyimq is a set of Python bindings to Open Message Queue (also known as the Glassfish Message Queue, formerly known as the Sun Java System Message Queue and informally known as IMQ).
This software wraps the Sun GlassFish Message Queue C runtime library in Python, modelling the implied object oriented design of the C interface.
The most common message queue usage patterns are supported, including asynchronous message consumers.
Contents¶
A Quick Example¶
This example shows a simple consumer, which simply retrieves messages and prints them.
#!/usr/bin/env python
import sys, os, optparse
if not 'MQ_LOG_LEVEL' in os.environ:
os.environ['MQ_LOG_LEVEL'] = '-1'
from imq import MQConnection, MQMessage
from imq import MQ_BROKER_HOST_PROPERTY, MQ_BROKER_PORT_PROPERTY, \
MQ_CONNECTION_TYPE_PROPERTY, MQ_CLIENT_ACKNOWLEDGE, MQ_SESSION_SYNC_RECEIVE, \
MQ_QUEUE_DESTINATION, MQ_TOPIC_DESTINATION, MQ_TEXT_MESSAGE
from imq import MQ_STRING_TYPE, MQ_INT32_TYPE
def consumer(host, port, name, type):
conn = MQConnection({MQ_BROKER_HOST_PROPERTY: (MQ_STRING_TYPE, host),
MQ_BROKER_PORT_PROPERTY: (MQ_INT32_TYPE, port),
MQ_CONNECTION_TYPE_PROPERTY: (MQ_STRING_TYPE, "TCP")}, "guest", "guest")
sess = conn.create_session(False, MQ_CLIENT_ACKNOWLEDGE, MQ_SESSION_SYNC_RECEIVE)
cons = sess.create_consumer(sess.create_destination(name, type))
conn.start()
while True:
mess = cons.receive_message_wait()
if mess.type() != MQ_TEXT_MESSAGE:
mess.acknowledge_messages()
continue
text = mess.get_text()
sys.stdout.write("Received message: " + mess.get_text() + "\n")
sys.stdout.flush()
mess.acknowledge_messages()
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option("--host", action="store", dest="host", default="localhost")
parser.add_option("--port", action="store", dest="port", default=7676, type="int")
parser.add_option("--destination_name", action="store", dest="destination_name", default="example_producerconsumer_dest")
parser.add_option("--type", action="store", dest="type", choices=("q", "t",), default="q")
(options, args) = parser.parse_args()
args = {'host' : options.host, 'port' : options.port, 'name' : options.destination_name,
'type' : 't' == options.type and MQ_TOPIC_DESTINATION or MQ_QUEUE_DESTINATION}
consumer(**args)