环境准备
- centos7 YUM安装rabbitmq-server
- 安装pika模块(pip安装)
.1 基本用法
生产者
#!bin/env python
# -*- coding: UTF-8 -*-
import pika
#指定链接参数
connection = pika.BlockingConnection(
pika.ConnectionParameters('localhost')
)
#创建管道
channel = connection.channel()
#声明queue
channel.queue_declare(queue='hello')
channel.publish(
exchange='',
routing_key='hello',
body='Hello world!',
properties=pika.BasicProperties(
delivery_mode=2 #数据持久化persistent
)
)
print("[X] Send Hello world!")
#关闭connection
connection.close()
执行生产者端之后,queue会一直存在,可以在rabbitmq-server端执行rabbitmqctl list_queues
查看队列的名称和个数
消费者
#!bin/env python
# -*- coding: UTF-8 -*-
import pika
#建立一个连接
connection = pika.BlockingConnection(
pika.ConnectionParameters('localhost')
)
#声明管道
channel = connection.channel()
#声明队列(初始化接收消息,指定接收哪个queue的数据)
queue = channel.queue_declare(queue='hello',durable=True)
#回调函数(消费函数)
def callback(ch, method, properties, body):
print("[X] Recevied %r" %body)
time.sleep(10)
ch.basic_ack(delivery_tag=method.delivery_tag) #终止队列 不加此行queue会一直存在
#consumer空闲则轮询接收消息
channel.basic_qos(prefetch_count=1)
channel.basic_consume(
callable, #消费函数
queue='hello',
# no_ack=True #一般不加
)
print("[*] Waiting for messages. To exit press CTRL+C")
channel.start_consuming()
要点:
- ch.basic_ack(delivery_tag=method.delivery_tag)
- 终止队列之后执行rabbitmqctl list_queues队列名还在,个数为0
- queue保存在内存中,重启rabbitmq-server,队列会消失
- 要想实现队列持久化需要在客户端和服务端
queue_declare()
中添加durable=True
参数- 这样一来重启rabbit之后queue还在,但是queue中的数据会丢失
- 消息和队列持久化——在producer端publish中加上delivery_mode=2,这样在rabbitmq-server重启之后没有手动结束的queue依然存在,queue中的数据也依然存在
exchange的三种types:
1. fanout:所以bind到此exchange的queue都可以接收到消息
2. direct:通过routingKey和exchange决定哪个queue可以接收到消息
3. topic:所有符合routingKey的routingKey所bind的queue可以接收到消息
fanout模式:producer
#!bin/env python
# -*- coding: UTF-8 -*-
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost'))
channel = connection.channel()
#不在声明管道,而是声明交换器,指定交换器名称和类型
channel.exchange_declare(exchange='task1',type='fanout')
message = "Hello World!"
channel.publish(
exchange='task1',
routing_key='',
body=message #这便不在指定queue,因为是fanout类型
)
print("[*] Send %s Done, %message")
connection.close()
fanout模式:producer
#!bin/env python
# -*- coding: UTF-8 -*-
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost'))
channel = connection.channel()
channel.exchange_declare(exchage='task1',type='fanout')
#不指定queue名,让其随机生成一个queue
result = channel.queue.declare(exclusive=True)
#获取queueName
queue_name = result.method.queue
#将queue绑定到指定的转发器上
channel.queue_bind(exchange='task1',queue=queue_name)
print("[*] Waiting for task1,To exit press CTRL+C")
def callback(ch, method, properties, body):
print("[*] %s" %body)
channel.basic_consume(callback,queue=queue_name,no_ack=True)
channel.start_consuming()
direct模式:producer