RabbitMQ是一個在AMQP基礎上完整的,可服用的企業消息系統。他遵循Mozilla Public License開源協議。

MQ全稱為Message Queue,消息隊列(MQ)是一種應用程序對應用程序的通信方法。

應用程序通過讀寫出入隊列的消息(針對應用程序的數據)來通信,而無需專用連接來鏈接它們。

消息傳遞指的是程序之間通過在消息中發送數據進行通信,而不是通過直接調用彼此來通信,直接調用通常是用於諸如遠程過程調用的技術。

隊列的使用除去了接收和發送應用程序同時執行的要求。

RabbitMQ安裝

安裝配置epel源
   $ rpm -ivh http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
 
安裝erlang
   $ yum -y install erlang
 
安裝RabbitMQ
   $ yum -y install rabbitmq-server

注意:service rabbitmq-server start/stop

 安裝API

pip install pika
or
easy_install pika
or
源碼
 
https://pypi.python.org/pypi/pika

使用API操作RabbitMQ

基於Queue實現生產者消費者模型

python實現snmp agent_python

python實現snmp agent_python_02

1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import Queue
 4 import threading
 5 
 6 
 7 message = Queue.Queue(10)
 8 
 9 
10 def producer(i):
11     while True:
12         message.put(i)
13 
14 
15 def consumer(i):
16     while True:
17         msg = message.get()
18 
19 
20 for i in range(12):
21     t = threading.Thread(target=producer, args=(i,))
22     t.start()
23 
24 for i in range(10):
25     t = threading.Thread(target=consumer, args=(i,))
26     t.start()

基於Queue

 

對於RabbitMQ來説,生產和消費不再針對內存裏的一個Queue對象,而是某台服務器上的RabbitMQ Server實現的消息隊列。

生產者:

1 #!/usr/bin/env python
 2 import pika
 3  
 4 # ######################### 生產者 #########################
 5  
 6 connection = pika.BlockingConnection(pika.ConnectionParameters(
 7         host='localhost'))
 8 channel = connection.channel()
 9  
10 channel.queue_declare(queue='hello')
11  
12 channel.basic_publish(exchange='',
13                       routing_key='hello',
14                       body='Hello World!')
15 print(" [x] Sent 'Hello World!'")
16 connection.close()

消費者:

1 #!/usr/bin/env python
 2 import pika
 3  
 4 # ########################## 消費者 ##########################
 5  
 6 connection = pika.BlockingConnection(pika.ConnectionParameters(
 7         host='localhost'))
 8 channel = connection.channel()
 9  
10 channel.queue_declare(queue='hello')
11  
12 def callback(ch, method, properties, body):
13     print(" [x] Received %r" % body)
14  
15 channel.basic_consume(callback,
16                       queue='hello',
17                       no_ack=True)
18  
19 print(' [*] Waiting for messages. To exit press CTRL+C')
20 channel.start_consuming()

 

1.acknowledgment消息不丟失

no-ack = False,如果消費者遇到情況(its channel is closed, connection is closed, or TCP connection is lost)掛掉了,那麼,RabbitMQ會重新將該任務添加到隊列中。

python實現snmp agent_python_03

python實現snmp agent_python實現snmp agent_04

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='10.211.55.4'))
channel = connection.channel()

channel.queue_declare(queue='hello')

def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)
    import time
    time.sleep(10)
    print 'ok'
    ch.basic_ack(delivery_tag = method.delivery_tag)

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

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

消費者

 

2.durable消息不丟失

python實現snmp agent_python_05

python實現snmp agent_python_06

#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='10.211.55.4'))
channel = connection.channel()

# make message persistent
channel.queue_declare(queue='hello', durable=True)

channel.basic_publish(exchange='',
                      routing_key='hello',
                      body='Hello World!',
                      properties=pika.BasicProperties(
                          delivery_mode=2, # make message persistent
                      ))
print(" [x] Sent 'Hello World!'")
connection.close()

生產者

python實現snmp agent_數據_07

python實現snmp agent_數據_08

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='10.211.55.4'))
channel = connection.channel()

# make message persistent
channel.queue_declare(queue='hello', durable=True)


def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)
    import time
    time.sleep(10)
    print 'ok'
    ch.basic_ack(delivery_tag = method.delivery_tag)

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

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

消費者

 

3.消費獲取順序

默認消息隊列裏的數據是按照順序被消費者拿走,例如:消費者1 去隊列中獲取 奇數 序列的任務,消費者1去隊列中獲取 偶數 序列的任務。

channel.basic_qos(prefetch_count=1) 表示誰來誰取,不再按照奇偶數排列

python實現snmp agent_python_09

python實現snmp agent_數據_10

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='10.211.55.4'))
channel = connection.channel()

# make message persistent
channel.queue_declare(queue='hello')


def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)
    import time
    time.sleep(10)
    print 'ok'
    ch.basic_ack(delivery_tag = method.delivery_tag)

channel.basic_qos(prefetch_count=1)

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

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

消費者

 

4.發佈訂閲

python實現snmp agent_數據_11

發佈訂閲和簡單的消息隊列區別在於,發佈訂閲會將消息發送給所有的訂閲者,而消息隊列中的數據被消費一次便消失。

所以,RabbitMQ實現發佈和訂閲時,會為每一個訂閲者創建一個隊列,而發佈者發佈消息時,會將消息放置在所有相關隊列中。

 exchange type = fanout

python實現snmp agent_python實現snmp agent_12

python實現snmp agent_python_13

#!/usr/bin/env python
import pika
import sys

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

channel.exchange_declare(exchange='logs',
                         type='fanout')

message = ' '.join(sys.argv[1:]) or "info: Hello World!"
channel.basic_publish(exchange='logs',
                      routing_key='',
                      body=message)
print(" [x] Sent %r" % message)
connection.close()

發佈者

python實現snmp agent_python_14

python實現snmp agent_python_15

#!/usr/bin/env python
import pika

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

channel.exchange_declare(exchange='logs',
                         type='fanout')

result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue

channel.queue_bind(exchange='logs',
                   queue=queue_name)

print(' [*] Waiting for logs. To exit press CTRL+C')

def callback(ch, method, properties, body):
    print(" [x] %r" % body)

channel.basic_consume(callback,
                      queue=queue_name,
                      no_ack=True)

channel.start_consuming()

訂閲者

 

5.關鍵字發送

python實現snmp agent_應用程序_16

 exchange type = direct

之前事例,發送消息時明確指定某個隊列並向其中發送消息,RabbitMQ還支持根據關鍵字發送,即:隊列綁定關鍵字,發送者將數據根據關鍵字發送到消息exchange,exchange根據 關鍵字 判定應該將數據發送至指定隊列。

python實現snmp agent_數據_17

python實現snmp agent_python_18

1 #!/usr/bin/env python
 2 import pika
 3 import sys
 4 
 5 connection = pika.BlockingConnection(pika.ConnectionParameters(
 6         host='localhost'))
 7 channel = connection.channel()
 8 
 9 channel.exchange_declare(exchange='direct_logs',
10                          type='direct')
11 
12 result = channel.queue_declare(exclusive=True)
13 queue_name = result.method.queue
14 
15 severities = sys.argv[1:]
16 if not severities:
17     sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0])
18     sys.exit(1)
19 
20 for severity in severities:
21     channel.queue_bind(exchange='direct_logs',
22                        queue=queue_name,
23                        routing_key=severity)
24 
25 print(' [*] Waiting for logs. To exit press CTRL+C')
26 
27 def callback(ch, method, properties, body):
28     print(" [x] %r:%r" % (method.routing_key, body))
29 
30 channel.basic_consume(callback,
31                       queue=queue_name,
32                       no_ack=True)
33 
34 channel.start_consuming()

消費者

python實現snmp agent_應用程序_19

python實現snmp agent_應用程序_20

1 #!/usr/bin/env python
 2 import pika
 3 import sys
 4 
 5 connection = pika.BlockingConnection(pika.ConnectionParameters(
 6         host='localhost'))
 7 channel = connection.channel()
 8 
 9 channel.exchange_declare(exchange='direct_logs',
10                          type='direct')
11 
12 severity = sys.argv[1] if len(sys.argv) > 1 else 'info'
13 message = ' '.join(sys.argv[2:]) or 'Hello World!'
14 channel.basic_publish(exchange='direct_logs',
15                       routing_key=severity,
16                       body=message)
17 print(" [x] Sent %r:%r" % (severity, message))
18 connection.close()

生產者

 

6.模糊匹配

python實現snmp agent_python實現snmp agent_21

 exchange type = topic

在topic類型下,可以讓隊列綁定幾個模糊的關鍵字,之後發送者將數據發送到exchange,exchange將傳入”路由值“和 ”關鍵字“進行匹配,匹配成功,則將數據發送到指定隊列。

  • # 表示可以匹配 0 個 或 多個 單詞
  • *  表示只能匹配 一個 單詞
1 發送者路由值              隊列中
2 old.boy.python          old.*  -- 不匹配
3 old.boy.python          old.#  -- 匹配

python實現snmp agent_python_22

python實現snmp agent_python_23

1 #!/usr/bin/env python
 2 import pika
 3 import sys
 4 
 5 connection = pika.BlockingConnection(pika.ConnectionParameters(
 6         host='localhost'))
 7 channel = connection.channel()
 8 
 9 channel.exchange_declare(exchange='topic_logs',
10                          type='topic')
11 
12 result = channel.queue_declare(exclusive=True)
13 queue_name = result.method.queue
14 
15 binding_keys = sys.argv[1:]
16 if not binding_keys:
17     sys.stderr.write("Usage: %s [binding_key]...\n" % sys.argv[0])
18     sys.exit(1)
19 
20 for binding_key in binding_keys:
21     channel.queue_bind(exchange='topic_logs',
22                        queue=queue_name,
23                        routing_key=binding_key)
24 
25 print(' [*] Waiting for logs. To exit press CTRL+C')
26 
27 def callback(ch, method, properties, body):
28     print(" [x] %r:%r" % (method.routing_key, body))
29 
30 channel.basic_consume(callback,
31                       queue=queue_name,
32                       no_ack=True)
33 
34 channel.start_consuming()

消費者

python實現snmp agent_應用程序_24

python實現snmp agent_python實現snmp agent_25

1 #!/usr/bin/env python
 2 import pika
 3 import sys
 4 
 5 connection = pika.BlockingConnection(pika.ConnectionParameters(
 6         host='localhost'))
 7 channel = connection.channel()
 8 
 9 channel.exchange_declare(exchange='topic_logs',
10                          type='topic')
11 
12 routing_key = sys.argv[1] if len(sys.argv) > 1 else 'anonymous.info'
13 message = ' '.join(sys.argv[2:]) or 'Hello World!'
14 channel.basic_publish(exchange='topic_logs',
15                       routing_key=routing_key,
16                       body=message)
17 print(" [x] Sent %r:%r" % (routing_key, message))
18 connection.close()

生產者

python實現snmp agent_python實現snmp agent_26

python實現snmp agent_數據_27

1 sudo rabbitmqctl add_user alex 123
 2 # 設置用户為administrator角色
 3 sudo rabbitmqctl set_user_tags alex administrator
 4 # 設置權限
 5 sudo rabbitmqctl set_permissions -p "/" alex '.''.''.'
 6 
 7 # 然後重啓rabbiMQ服務
 8 sudo /etc/init.d/rabbitmq-server restart
 9  
10 # 然後可以使用剛才的用户遠程連接rabbitmq server了。
11 
12 
13 ------------------------------
14 credentials = pika.PlainCredentials("alex","123")
15 
16 connection = pika.BlockingConnection(pika.ConnectionParameters('192.168.14.47',credentials=credentials))

注意事項