Skip to content

Python with RabbitMQ to create direct Exchange

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

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


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


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='direct')
		result = channel.queue_declare(exclusive=True)
		queue_name = result.method.queue

		channel.queue_bind(exchange='logs',
						   queue=queue_name,
						   routing_key='test')
		channel.basic_consume(get,
							  queue=queue_name,
							  no_ack=True)
		channel.start_consuming()
	except ProbableAccessDeniedError:
		print 'Access Error'
	except ProbableAuthenticationError:
		print 'Auth Error'
	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='direct')

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