python16_day11【MQ、Redis、Memcache】

來源:互聯網
上載者:User

標籤:waiting   安裝   arch   release   接收   排隊   producer   發送資料   python   

一、RabbitMQ

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

MQ全稱為Message Queue, 訊息佇列(MQ)是一種應用程式對應用程式的通訊方法。應用程式通過讀寫出入隊列的訊息(針對應用程式的資料)來通訊,而無需專用連線來連結它們。消 息傳遞指的是程式之間通過在訊息中發送資料進行通訊,而不是通過直接調用彼此來通訊,直接調用通常是用於諸如遠端程序呼叫的技術。排隊指的是應用程式通過 隊列來通訊。隊列的使用除去了接收和發送應用程式同時執行的要求。

 

  1.RabbitMQ install

1 安裝配置epel源2    $ rpm -ivh http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm3  4 安裝erlang5    $ yum -y install erlang6  7 安裝RabbitMQ8    $ yum -y install rabbitmq-server
  

注意:service rabbitmq-server start/stop

  2. Python API install  

1 pip install pika2 or3 easy_install pika4 or5 源碼6 https://pypi.python.org/pypi/pika

  3.基於QUEUE實現生產消費模型

 1 import Queue 2 import threading 3  4  5 message = Queue.Queue(10) 6  7  8 def producer(i): 9     while True:10         message.put(i)11 12 13 def consumer(i):14     while True:15         msg = message.get()16 17 18 for i in range(12):19     t = threading.Thread(target=producer, args=(i,))20     t.start()21 22 for i in range(10):23     t = threading.Thread(target=consumer, args=(i,))24     t.start()

  4.基於RabbitMQ

  對於RabbitMQ來說,生產和消費不再針對記憶體裡的一個Queue對象,而是某台伺服器上的RabbitMQ Server實現的訊息佇列。

 1 import pika 2   3 # ######################### 生產者 ######################### 4   5 connection = pika.BlockingConnection(pika.ConnectionParameters( 6         host=‘localhost‘)) 7 channel = connection.channel() 8   9 channel.queue_declare(queue=‘hello‘)10  11 channel.basic_publish(exchange=‘‘,12                       routing_key=‘hello‘,13                       body=‘Hello World!‘)14 print(" [x] Sent ‘Hello World!‘")15 connection.close()16 17 18  19 # ########################## 消費者 ##########################20 import pika21 connection = pika.BlockingConnection(pika.ConnectionParameters(22         host=‘localhost‘))23 channel = connection.channel()24  25 channel.queue_declare(queue=‘hello‘)26  27 def callback(ch, method, properties, body):28     print(" [x] Received %r" % body)29  30 channel.basic_consume(callback,31                       queue=‘hello‘,32                       no_ack=True)33  34 print(‘ [*] Waiting for messages. To exit press CTRL+C‘)35 channel.start_consuming()

 

python16_day11【MQ、Redis、Memcache】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.