1,rabbitMQ 与 ptyhon 进程 queue 区别. 进程 queue 主要用户 Python 父子进程之间或者统一进程不同子进程. rabbit 可以用户不同语言之前的相互交流, socket 可以实现同样功能, 但是较为复杂.
2, rabbitMQ 消息轮训. 一个生产者对多个消费者时候. 会自动将消息轮训给不同消费者.
- # Author : xiajinqi
- import pika
- connetction = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
- channel = connetction.channel()
- channel.queue_declare(queue='hello')
- # 1 个生产着, 三个消费者, 会自动轮训, 其中一个消费者宕机后, 消息会自动发给其他消费者处理.
- channel.basic_publish(exchange='',routing_key='hello',body='hello world!')
- print("消息已经发送")
- channel.close()
- # Author : xiajinqi
- import pika
- import time
- connetction = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
- channel = connetction.channel()
- channel.queue_declare(queue='hello') #避免生产者后启动, 没有这个队列报错. 所以在此申明
- def callback(ch,method,properties,body):
- '''
- :param ch: 管道对象内存地址
- :param method: 发消息给谁的申明信息
- :param properties:
- :param body:
- :return:
- '''
- print(ch,method,properties,body)
- ch.basic_ack(delivery_tag=method.delivery_tag) #执行完以后告诉服务端
- # time.sleep(30)
- pass
- ## 申明收到调用 callbak 处理 no_ack 默认为 false 消息不会丢失, 表示需要客户端回调函数处理完, 主动告诉服务端已经处理完. 为 true 断电消息会丢失
- #channel.basic_consume(callback,queue='hello',no_ack='True')
- channel.basic_consume(callback,queue='hello')
- print("开始收消息")
- channel.start_consuming()
3, 服务端消息持久化声明
- channel.queue_declare(queue='hello1',durable='True') # durable 队列持久化申明
- # 1 个生产着, 三个消费者, 会自动轮训, 其中一个消费者宕机后, 消息会自动发给其他消费者处理.
- #delivery_mode 消息持久化声明
- channel.basic_publish(exchange='',routing_key='hello1',body='hello world!',properties=pika.BasicProperties(delivery_mode=2))
来源: http://www.bubuko.com/infodetail-2742808.html