CodyKochmann
4/17/2017 - 3:34 PM

this is an example of how both sending and receiving messages in rabbitmq works in python

this is an example of how both sending and receiving messages in rabbitmq works in python

#!/usr/bin/env python
# by: Cody Kochmann
# this is an example of how both sending and receiving messages in rabbitmq works in python

from pika import BlockingConnection, ConnectionParameters

def send_to_queue(host, queue_name, message):
	""" pushes a message to a queue """
	assert type(host) == str
	assert type(queue_name) == str
	assert type(message) == str
	connection = BlockingConnection(ConnectionParameters(host=host))
	channel = connection.channel()
	channel.queue_declare(queue=queue_name)
	channel.basic_publish(exchange='', routing_key=queue_name, body=message)
	connection.close()


def recieve_from_queue(host, queue_name, callback):
	""" recieves messages from queues """
	assert type(host) == str
	assert type(queue_name) == str
	assert callable(callback)
	connection = BlockingConnection(ConnectionParameters(host=host))
	channel = connection.channel()
	channel.queue_declare(queue=queue_name)
	channel.basic_consume(callback, queue=queue_name, no_ack=True)
	channel.start_consuming()


if __name__ == '__main__':
	send_to_queue('localhost', 'hello', 'this is the first message before the listener was called')
	send_to_queue('localhost', 'hello', 'this is the second message before the listener was called')
	send_to_queue('localhost', 'hello', 'this is the third message before the listener was called')

	# timer is just to background things
	from threading import Timer 

	def callback(*args):
		print("recieved: {}".format(args[-1]))

	# runs the listener in the background
	print('starting consumer')
	Timer(0, lambda:recieve_from_queue(host='localhost', queue_name='hello', callback=callback)).start()

	send_to_queue('localhost', 'hello', 'this is the fourth message after the listener was called')
	send_to_queue('localhost', 'hello', 'this is the fifth message after the listener was called')
	send_to_queue('localhost', 'hello', 'this is the sixth message after the listener was called')