python rabbit 消费者 长连接
时间: 2023-11-23 22:56:23 浏览: 115
以下是Python RabbitMQ消费者长连接的示例代码:
```python
import pika
import logging
class RabbitConsumer:
def __init__(self, sv_addr, sv_port, username, passwd):
self.sv_addr = sv_addr
self.sv_port = sv_port
self.username = username
self.passwd = passwd
self.connection = None
self.channel = None
self.logger = logging.getLogger(__name__)
def connect(self):
credentials = pika.PlainCredentials(self.username, self.passwd)
parameters = pika.ConnectionParameters(self.sv_addr, self.sv_port, '/', credentials)
self.connection = pika.BlockingConnection(parameters)
self.channel = self.connection.channel()
self.channel.basic_qos(prefetch_count=1)
def consume(self, queue_name, callback):
while True:
try:
self.channel.basic_consume(queue_name, callback)
self.channel.start_consuming()
except pika.exceptions.ConnectionClosed:
self.logger.error("reconnect rabbitmq: %s:%s" %(self.sv_addr, self.sv_port))
self.connect()
def close(self):
self.connection.close()
def callback(ch, method, properties, body):
print("Received message: %s" % body)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
consumer = RabbitConsumer('localhost', 5672, 'guest', 'guest')
consumer.connect()
consumer.consume('test_queue', callback)
```
在这个示例中,我们使用了pika库来连接RabbitMQ服务器。我们创建了一个RabbitConsumer类,它包含了连接到RabbitMQ服务器、消费队列和关闭连接的方法。我们还定义了一个回调函数,它将在每次接收到消息时被调用。
在主函数中,我们创建了一个RabbitConsumer对象并连接到RabbitMQ服务器。然后,我们调用consume方法来开始消费队列。如果连接被关闭,我们将重新连接到RabbitMQ服务器。
阅读全文