天天看点

RabbitMQ消息分发轮询

我们首先下载pika,以及rabbitMQ,和ir语言,rabbitMQ是由ir语言编写的

消息队列的使用过程大概如下:

(1)客户端连接到消息队列服务器,打开一个channel。

channel:消息通道,在客户端的每个连接里,可建立多个channel,每个channel代表一个会话任务。

(2)客户端声明一个exchange,并设置相关属性。

Exchange:消息交换机,它指定消息按什么规则,路由到哪个队列。

(3)客户端声明一个queue,并设置相关属性。

Queue:消息队列载体,每个消息都会被投入到一个或多个队列。

(4)客户端使用routing key,在exchange和queue之间建立好绑定关系。

Routing Key:路由关键字,exchange根据这个关键字进行消息投递。

(5)客户端投递消息到exchange。

接下来写一个生产者:

import pika

connection = pika.BlockingConnection(

   pika.ConnectionParameters('localhost'))

channel = connection.channel()#先通过socket建立一个实例,创建一个新的频道

# 声明queue

channel.queue_declare(queue='hello')# 注意此处需要声明一个管道或者称之为队列,在此处出发消息 同时客户端与服务端都需要

# n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.

channel.basic_publish(exchange='',

                     routing_key='hello',#queue名字#路由键,写明将消息发往哪个队列,本例是将消息发往队列pikamq

                     body='Hello World!')# 消息内容

print(" [x] Sent 'Hello World!'")# 当生产者发送完消息后,可选择关闭连接

connection.close()

消费者:

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost' ))

channel = connection.channel()

channel.queue_declare(queue='hello')

def callback(ch, method, properties, body):

         print('--->',ch,method,properties)

         print(" [x] Received %r"%body)

channel.basic_consume(callback,

                     queue='hello',

                     #no_ack=True  #此处有的代码加了,但是python系统会自带,同时加了之后,一旦等待时间过长,生产者发送的消息,无法转移到另一个消费者中

                     )

channel.start_consuming()

      本文转自眉间雪 51CTO博客,原文链接:http://blog.51cto.com/13348847/1979026,如需转载请自行联系原作者