rabbitmq學習:

消息隊列(消息中間件)常見的有三種:RabbitMQ、ActiveMQ、ZeroMQhtml

這裏要說的是RabbitMQ。python

須要明確的幾個概念:函數

Broker: 翻譯爲中文應該是「經紀人」、「中間人」吧,就是指RbbitMQ服務自己spa

vhost: 虛擬主機,作權限控制用的,每一個包含一組exchanges, queues,bindings翻譯

Exchange: 「交換機」,能夠理解爲有路由表(binding)的路由程序,而每一個消息都有一個routing key的屬性,嗯,和路由原理很相像。code

Queue:  消息的終點,消息到達這裏後,等待着被消費者取走server

Binding: 就是路由規則htm

Routing Key: 至關於ip地址中間件

producer:  嗯blog

consumer: 嗯

channel:  --這個不是很明白呀,通訊流?會話?

 

python可使用的庫有py-amqplib, txAMQP, pika,我跟着tutorial學了pika

 

首先,須要與RabbitMQ server創建鏈接,並在鏈接中創建channel

import pika
connection = pika.BlokingConnection(pika.ConnectionParameters('localhost', 5672))
channel = connection.channel()

第二步,須要確認接收隊列存在,若將消息發給一個不存在的隊列,RabbitMQ會丟棄這個消息。咱們來建立一個叫作hello的隊列吧:

channel.queue_declare(queue='hello')

第三步, 這時已經能夠發送消息了,消息必然要通過exchange才能到達queue,關於exchange,附錄的文章中有比較好的說明。這裏只需選擇默認exchange。

channel.basic_publish(exchange='',
                      routing_key='hello',
                      body='Hello Word!')

結束程序前,須要確認network buffers 已經被刷新,關閉鏈接便可。

connection.close()

-----------------------------------------------------------------------

Listing queues

You may wish to see what queues RabbitMQ has and how many messages are in them. You can do it (as a privileged user) using the rabbitmqctl tool:

$ sudo rabbitmqctl list_queues
Listing queues ...
hello    0
...done.

(omit sudo on Windows)

------------------------------------------------------------------------

 

==============================================================

 

該consumer端到隊列裏面去消息了,一樣的,創建鏈接和channel,嗯代碼同前。在開始以前,首先確認下隊列已經存在,跟producer端同樣的,由於不知道是哪邊程序先啓動,這樣作很保險。

channel.queue_declare(queue='hello')

接收端獲得一個消息,會調用用戶定義的回調函數,那麼咱們先定義一個回調函數吧。

簡單點的,打印消息

def callback(ch, method, properties, body):
    print 「 Received %r" % (body,)

而後告訴RabbitMQ我定義的這個回調函數應該處理hello隊列中的消息(這要求此隊列必須存在,咱們以前用queue_declare確認過了):

channel.basic_consume(callback,
                      queue='hello',
                      no_ack=True)

好了,進入等待狀態吧,有消息過來了,就會調用以前定義好的回調函數了:

channel.start_consuming()

 

 

資源連接:

官網tutorial:    http://www.rabbitmq.com/tutorials/tutorial-one-python.html

[翻譯] [RabbitMQ+Python入門經典] 兔子和兔子窩:http://blog.ftofficer.com/2010/03/translation-rabbitmq-python-rabbits-and-warrens/

原文: https://bmark.us/bmark/readable/6067c44d09ee21

消息隊列RabbitMQ入門介紹  http://www.nsbeta.info/archives/200

相關文章
相關標籤/搜索