在RabbitMQ中,有五种消息模型,分别是简单模型(Simple)、工作队列模型(Work Queue)、发布/订阅模型(Publish/Subscribe)、路由模型(Routing)和主题模型(Topics)。
- 简单模型(Simple):一个生产者,一个消费者。
生产者代码:
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!')
print(" [x] Sent 'Hello World!'")
消费者代码:
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
print(f" [x] Received {body}")
channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
- 工作队列模型(Work Queue):多个消费者竞争从队列中获取任务。
与简单模型的区别在于,需要在队列中声明basic_qos(prefetch_count=1)
,以保证一条消息只会被一个消费者接收处理。
生产者与简单模型相同。
消费者代码:
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
print(f" [x] Received {body}")
channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
- 发布/订阅模型(Publish/Subscribe):一个生产者,多个消费者,生产者发送的消息,所有订阅的消费者都可以接收到。
生产者代码:
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='logs', exchange_type='fanout')
message = 'Hello World!'
channel.basic_publish(exchange='logs',
routing_key='',
body=message)
print(f" [x] Sent {message}")
消费者代码:
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='logs', exchange_type='fanout')
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
channel.queue_bind(excha