1、生产者和消费者:生产者创建消息,然后发布到代理服务器的队列中,代理服务器会把消息发送给感兴趣的接受方。消费者链接到代理服务器,并订阅到队列上,接收消息
2、信道channel:信道是“真实的”TCP连接内的虚拟连接,AMQP的命令都是通过信道发送的。在一条TCP连接上可以创建多条信道
3、队列:存放消息的地方,队列通过路由键绑定到交换机,生产者通过交换机将消息发送到队列中。
4、交换机和绑定: 生产者发布消息时,先将消息发送到交换机,通过交换机与队列的绑定规则将消息发送到队列。常见的交换机有topic、fanout、direct
direct交换机:direct交换机是包含空白字符串的默认交换机,当声明队列时会主动绑定到默认交换机,并且以队列名称为路由键
fanout交换机:这种交换机会将收到的消息广播到绑定的队列
topic交换机:topic交换机可以通过路由键的正则表达式将消息发送到多个队列
5、vhost:虚拟主机,就是一个AMQP服务,拥有自己的队列、交换机和绑定、权限,vhost使得一个AMQP可以为多个应用程序服务
6、持久化:持久化指的是能从AMQP服务器崩溃中恢复消息,要实现消息的持久化,必须要:把消息的投递模式设置为2(持久化),发布到持久化的交换机,到达持久化的队列
下面是一个demo:
hello-world-producer.py
import pika, sys
credentials = pika.PlainCredentials("guest", "guest")
conn_params = pika.ConnectionParameters("localhost",
credentials = credentials)
conn_broker = pika.BlockingConnection(conn_params)
channel = conn_broker.channel()
channel.exchange_declare(exchange="hello-exchange",
type = "direct",
passive = False,
durable = True,
auto_delete = False)
msg = sys.argv[1]
msg_props = pika.BasicProperties()
msg_props.content_type = "text/plain"
channel.basic_publish(body=msg,
exchange = "hello-exchange",
properties = msg_props,
routing_key = "hola")
hello-world-consume.py
import pika
credentials = pika.PlainCredentials("guest", "guest")
conn_params = pika.ConnectionParameters("localhost",
credentials = credentials)
conn_broker = pika.BlockingConnection(conn_params)
channel = conn_broker.channel()
channel.exchange_declare(exchange = "hello-exchange",
type = "direct",
passive = False,
durable = True,
auto_delete = False)
channel.queue_declare(queue = "hello-queue")
channel.queue_bind(queue="hello-queue",
exchange = "hello-exchange",
routing_key = "hola")
def msg_consumer(channel, method, header, body):
channel.basic_ack(delivery_tag = method.delivery_tag)
if body == "quit":
channel.basic_cancel(consumer_tag = "hello-sonsumer")
channel.stop_consuming()
else:
print body
return
channel.basic_consume(msg_consumer,
queue = "hello-queue",
consumer_tag = "hello-consumer")
channel.start_consuming()
参考《rabbitmq实战》第二章