python mq工具类
时间: 2023-11-22 16:50:21 浏览: 105
根据提供的引用内容,以下是一个Python的MQ工具类的示例:
```python
import pika
class MQTool:
def __init__(self, host, username, password):
self.host = host
self.username = username
self.password = password
self.connection = None
self.channel = None
def connect(self):
credentials = pika.PlainCredentials(self.username, self.password)
parameters = pika.ConnectionParameters(self.host, credentials=credentials)
self.connection = pika.BlockingConnection(parameters)
self.channel = self.connection.channel()
def publish(self, exchange, routing_key, message):
self.channel.basic_publish(exchange=exchange, routing_key=routing_key, body=message)
def consume(self, queue, callback):
self.channel.basic_consume(queue=queue, on_message_callback=callback, auto_ack=True)
self.channel.start_consuming()
def close(self):
self.connection.close()
```
使用示例:
```python
mq = MQTool('localhost', 'guest', 'guest')
mq.connect()
# 发布消息
mq.publish('exchange_name', 'routing_key', 'Hello, RabbitMQ!')
# 消费消息
def callback(ch, method, properties, body):
print("Received message:", body)
mq.consume('queue_name', callback)
# 关闭连接
mq.close()
```
这个示例使用了pika库来操作RabbitMQ消息队列。MQTool类封装了连接、发布和消费消息的功能,并提供了连接关闭的方法。
阅读全文