python+rabbitMQ实现生产者和消费者模式
(一)安装一个消息中间件,如:rabbitMQ
(二)生产者
sendmq.py
import pika import sys import time # 远程rabbitmq服务的配置信息 username = 'admin' # 指定远程rabbitmq的用户名密码 pwd = 'admin' ip_addr = '10.1.7.7' port_num = 5672 # 消息队列服务的连接和队列的创建 credentials = pika.PlainCredentials(username, pwd) connection = pika.BlockingConnection(pika.ConnectionParameters(ip_addr, port_num, '/', credentials)) channel = connection.channel() # 创建一个名为balance的队列,对queue进行durable持久化设为True(持久化第一步) channel.queue_declare(queue='balance', durable=True) message_str = 'Hello World!' for i in range(100000000): # n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange. channel.basic_publish( exchange='', routing_key='balance', # 写明将消息发送给队列balance body=message_str, # 要发送的消息 properties=pika.BasicProperties(delivery_mode=2, ) # 设置消息持久化(持久化第二步),将要发送的消息的属性标记为2,表示该消息要持久化 ) # 向消息队列发送一条消息 print(" [%s] Sent 'Hello World!'" % i) # time.sleep(0.2) connection.close() # 关闭消息队列服务的连接
运行sendmq.py文件,可以从以下方法查看队列中的消息数量。
一是,rabbitmq的管理界面,如下图所示:
二是,从服务器端命令查看
rabbitmqctl list_queues
(三)消费者
receivemq.py
import pika import sys import time # 远程rabbitmq服务的配置信息 username = 'admin' # 指定远程rabbitmq的用户名密码 pwd = 'admin' ip_addr = '10.1.7.7' port_num = 5672 credentials = pika.PlainCredentials(username, pwd) connection = pika.BlockingConnection(pika.ConnectionParameters(ip_addr, port_num, '/', credentials)) channel = connection.channel() # 消费成功的回调函数 def callback(ch, method, properties, body): print(" [%s] Received %r" % (time.time(), body)) # time.sleep(0.2) # 开始依次消费balance队列中的消息 channel.basic_consume(queue='balance', on_message_callback=callback, auto_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C') channel.start_consuming() # 启动消费
运行receivemq.py文件,可以从以下方法查看队列中的消息数量。
或者
rabbitmqctl list_queues
延伸:
systemctl status rabbitmq-server.service # 状态
systemctl restart rabbitmq-server.service # 重启