python对RabbitMQ常用操作的封装

#!/usr/bin/python
# -*- coding:utf-8 -*-

import pika

class Rabbit(object):

	def __init__(self,username,password,host,port=5672):
		self.host = str(host)
		self.port = int(port)
		self.crt = pika.PlainCredentials(username,password)
		self.conn = pika.BlockingConnection(pika.ConnectionParameters(host=self.host,
			port=self.port,credentials=self.crt))
		self.channel = self.conn.channel()

	def declare_queue(self,queue_name,is_durable):
		queue = self.channel.queue_declare(queue=queue_name,
			durable=is_durable)

	def produce(self,r_key,msg,ex=''):
		self.channel.basic_publish(exchange=ex,
			routing_key=r_key,
			body=msg,
			properties=pika.BasicProperties(
				delivery_mode=2 # make message persistent
				))

	def set_qos(self):
		self.channel.basic_qos(prefetch_count=1)

	def callback(cls,ch,method,properties,body):
		print(" [x] Received %r " % body)
		ch.basic_ack(delivery_tag=method.delivery_tag)

	def consume(self,queue_name,callback=None,no_ack=False):
		if callback==None:
			self.channel.basic_consume(self.callback,
				queue=queue_name,no_ack=False)
		else:
			self.channel.basic_consume(callback,
				queue=queue_name,no_ack=no_ack)
		self.channel.start_consuming()

	def msg_count(self,queue_name,is_durable=True):
		queue = self.channel.queue_declare(queue=queue_name,durable=is_durable)
		count = queue.method.message_count
		return count

	def close(self):
		self.conn.close()

 

你可能感兴趣的:(后端开发)