python 这是一个如何在rabbitmq中发送和接收消息在python中工作的示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 这是一个如何在rabbitmq中发送和接收消息在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')


以上是关于python 这是一个如何在rabbitmq中发送和接收消息在python中工作的示例的主要内容,如果未能解决你的问题,请参考以下文章

RabbitMq高级之如何保证消息发送可靠性

如何使用 Python 将 XML 文件发送到 RabbitMQ?

Python-RabbitMQ(简单发送模型)

Python-RabbitMQ(简单发送模型)

RabbitMQ如何实现延迟队列?

RabbitMQ发送消息+python