RabbitMq几种工作模式详细讲解
    		       		warning:
    		            这篇文章距离上次修改已过426天,其中的内容可能已经有所变动。
    		        
        		                
                RabbitMQ是一个消息代理,它接收和转发消息。RabbitMQ支持多种消息传递模式,包括简单的队列模式、工作队列模式、发布/订阅模式、路由模式、通配符模式等。
- 简单队列模式(Simple Queue)
 
简单的队列模式是最基本的消息队列模式,一个生产者发送消息到队列,一个消费者从队列中取消息。
生产者代码示例:
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!'")
 
connection.close()消费者代码示例:
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)
 
工作队列模式是多个消费者平分任务,每个消费者处理的任务是均衡的。
import pika
 
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
 
channel.queue_declare(queue='task_queue', durable=True)
 
message = 'Hello World!'
channel.basic_publish(exchange='',
                      routing_key='task_queue',
                      body=message,
                      properties=pika.BasicProperties(
                          delivery_mode=2,  # make message persistent
                      ))
print(f" [x] Sent {message}")
 
connection.close()
import pika
 
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
 
channel.queue_declare(queue='task_queue', durable=True)
 
def callback(ch, method, properties, body):
    print(f" [x] Received {body}")
 
channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue='task_queue', on_message_callback=callback)
 
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()- 发布/订阅模式(Publish/Subscribe)
 
发布/订阅模式是生产者发送消息到交换机,交换机根据规则将消息发送到多个队列。
import pika
 
conne           
评论已关闭