在 Python 中使用 RabbitMQ,您可以使用pika库和paho库进行常规的 RabbitMQ 操作。以下是一个基本的示例,展示了如何在 Python 中连接到 RabbitMQ、发布消息和消费消息,其中发布消息的模式主要分为路由模式和发布订阅模式。
一、pika库(路由模式)
订阅者(带断连重连)
import json
import time
from threading import Thread
import pika
def listen_msg(channel):
try:
# 声明exchange和queue
exchange_name = 'fireMonitoring'
queue_name = 'iot_monitor_queue'
routing_key = 'iot2monitor'
channel.exchange_declare(exchange=exchange_name, exchange_type='direct')
channel.queue_declare(queue=queue_name)
channel.queue_bind(exchange=exchange_name, queue=queue_name, routing_key=routing_key)
# 接收消息
def callback(ch, method, properties, body):
data = json.loads(body)
breakercode = data['breakerCode']
createtime = data['createTime']
print(" [x] Received: %r" % data)
channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)
print(' [*] Waiting for messages. To exit, press CTRL+C')
channel.start_consuming()
except Exception as e:
print('mq断开连接', e)
def status_check():
while True:
try:
credentials = pika.PlainCredentials('username', 'password')
parameters = pika.ConnectionParameters('ip', 5672, '/', credentials, heartbeat=5)
connection = pika.BlockingConnection(parameters)
channel = connection.channel()
listen_msg(channel)
except Exception as e:
time.sleep(5)
print('连接mq失败,重试中。。。')
t = Thread(target=status_check)
t.start()
发布者:
import json
import pika
def send_msg(m):
# 连接到RabbitMQ服务器
credentials = pika.PlainCredentials('username', 'password')
parameters = pika.ConnectionParameters('ip', '/', credentials)
connection = pika.BlockingConnection(parameters)
channel = connection.channel()
# 声明exchange和queue
exchange_name = 'fireMonitoring'
queue_name = 'iot_monitor_queue'
routing_key = 'iot2monitor'
channel.exchange_declare(exchange=exchange_name, exchange_type='direct')
channel.queue_declare(queue=queue_name)
channel.queue_bind(exchange=exchange_name, queue=queue_name, routing_key=routing_key)
# 发送消息
message = {
"Code": f"123456--{m}", # 编码
"Time": "2222" # 时间
}
channel.basic_publish(exchange=exchange_name, routing_key=routing_key, body=json.dumps(message))
print(" [x] Sent: %r" % message)
# 关闭连接
connection.close()
for i in range(10):
send_msg(i)
注:路由模式下如果多个订阅者同时订阅,将会轮换从队列里面取数据,并且数据被一个取走以后另一个就没这个数据了,两个订阅者接收到的数据加一起就是发布者发布的所有数据。
二、paho库(发布订阅模式)
订阅者(带断线重连)
import time
from threading import Thread
import paho.mqtt.client as mqtt
def listen_msg1(client):
try:
def on_disconnect(client, userdata, rc):
print('断开连接')
raise
# 处理消息
def on_message(client, userdata, msg):
print(456)
print("Received message: ", msg.payload.decode())
client.on_message = on_message
client.on_disconnect = on_disconnect
# 订阅主题
topic = "chat"
client.subscribe(topic, qos=0)
# 循环接收消息
client.loop_forever()
except Exception as e:
print(e)
def status_check():
while True:
try:
host = "ip" # RabbitMQ 服务器的主机名或 IP 地址
port = 1883 # RabbitMQ 服务器的端口号
username = "username" # RabbitMQ 用户名
password = "password" # RabbitMQ 密码
client = mqtt.Client()
client.username_pw_set(username, password)
client.connect(host, port, keepalive=5)
listen_msg1(client)
except Exception as e:
time.sleep(1)
print('连接mq失败,重试中。。。')
t = Thread(target=status_check)
t.start()
发布者
def send_msg1(d):
# paho mqtt连接发布
import paho.mqtt.client as mqtt
# 连接参数
host = "ip" # RabbitMQ 服务器的主机名或 IP 地址
port = 1883 # RabbitMQ 服务器的端口号
username = "username" # RabbitMQ 用户名
password = "password" # RabbitMQ 密码
# 连接到 RabbitMQ
client = mqtt.Client()
client.username_pw_set(username, password)
client.connect(host, port, keepalive=5)
# 发布消息
topic = "chat"
message = f"Hello, MQTT!---{i}"
client.publish(topic, message)
# 断开连接
client.disconnect()
for i in range(5):
send_msg1(i)
注:发布订阅模式下所有订阅者会接收到同样的数据,多个订阅者最终收到的数据是一致的。不存在差异,不排除网络问题导致的丢包问题导致的数据不一致。