Skip to content

Python with RabbitMQ to create fanout Exchange

Published: at 00:00
接收端
#coding=utf-8
__author__ = 'nate'

import pika
from pika.exceptions import ProbableAccessDeniedError
from pika.exceptions import ProbableAuthenticationError

if __name__ == '__main__':
	parameters = pika.URLParameters('amqp://nate:[email protected]:5672/test_vhost')
	conn = None
	channel = None
	try:
		conn = pika.BlockingConnection(parameters)
		channel = conn.channel()
		channel.exchange_declare(exchange='logs',
										  type='fanout')
		result = channel.queue_declare(exclusive=True)
		queue_name = result.method.queue

		channel.queue_bind(exchange='logs',
						   queue=queue_name)

		def get(ch, method, props, body):
			print 'message: %r' % body

		channel.basic_consume(get,
							  queue=queue_name,
							  no_ack=True)

		channel.start_consuming()
	except ProbableAccessDeniedError:
		print 'Access Denied'
	except ProbableAuthenticationError:
		print 'Authentication Error'
	except KeyboardInterrupt:
		print 'exit'
	finally:
		if channel:
			channel.close()
		if conn:
			conn.close()
发送端
#coding=utf-8
__author__ = 'nate'

import pika
from pika.exceptions import ProbableAccessDeniedError
from pika.exceptions import ProbableAuthenticationError


if __name__ == '__main__':
	parameters = pika.URLParameters('amqp://nate:[email protected]:5672/test_vhost')
	conn = None
	channel = None
	try:
		conn = pika.BlockingConnection(parameters)
		channel = conn.channel()
		channel.exchange_declare(exchange='logs',
								 type='fanout')

		channel.basic_publish(exchange='logs',
							  routing_key='',
							  body='This is Test')
		print 'sent'
	except ProbableAccessDeniedError:
		print 'Access Denied'
	except ProbableAuthenticationError:
		print 'Authentication Error'
	finally:
		if channel:
			channel.close()
		if conn:
			conn.close()