rabbitmq 工具类
时间: 2023-06-13 10:04:47 浏览: 119
以下是一个使用 Python 的 RabbitMQ 工具类,可以实现基本的消息队列操作:
```python
import pika
class RabbitMQ:
def __init__(self, host, port, username, password):
self.host = host
self.port = port
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,
self.port,
'/',
credentials)
self.connection = pika.BlockingConnection(parameters)
self.channel = self.connection.channel()
def declare_queue(self, queue_name):
self.channel.queue_declare(queue=queue_name)
def send_message(self, queue_name, message):
self.channel.basic_publish(exchange='',
routing_key=queue_name,
body=message)
def receive_message(self, queue_name):
method_frame, _, body = self.channel.basic_get(queue_name)
if method_frame:
self.channel.basic_ack(method_frame.delivery_tag)
return body.decode()
def close(self):
self.connection.close()
```
使用方法:
```python
# 实例化RabbitMQ对象
rabbitmq = RabbitMQ('localhost', 5672, 'guest', 'guest')
# 连接RabbitMQ服务器
rabbitmq.connect()
# 声明队列
rabbitmq.declare_queue('hello')
# 发送消息
rabbitmq.send_message('hello', 'Hello, RabbitMQ!')
# 接收消息
message = rabbitmq.receive_message('hello')
print(message)
# 关闭连接
rabbitmq.close()
```
需要注意的是,这个工具类只是一个简单的示例,实际使用时需要根据自己的需求进行修改和完善。
阅读全文