首先確定rabbitMQ已經安裝完成,也就是在安裝目錄下運行rabbitMQ-server能成功
之後進行如下兩個步驟:
首先創建一個hello_world_send.py
- import os
- import pika
- conn = None
- try:
- # 獲取連接
- conn = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
- # 獲取通道
- channel = conn.channel()
- # 在發送隊列前,需要確定隊列是否存在,如果不存在RabbitMQ將會丟棄,先創建隊列
- channel.queue_declare('hello')
- # 在RabbitMQ中發送消息,不是直接發送隊列,而是發送交換機(exchange),此處不多做研究,後面系列逐漸深入
- ret = channel.basic_publish(exchange='',
- routing_key='hello',
- body="Hello, World!")
- print " [x] Sent 'Hello World!'"
- print ret
- except Exception, e:
- raise e
- finally:
- if conn:
- conn.close()
然後創建一個hello_world_recv.py
-
- import os
- import pika
- conn = None
- def callback(ch, method, properties, body):
- """
- out body
- """
- print " [x] Recived ch {0}".format(ch)
- print " [x] Recived method {0}".format(method)
- print " [x] Recived properties {0}".format(properties)
- print " [x] Recived %r" % (body, )
- try:
- # get connection
- conn = pika.BlockingConnection(pika.ConnectionParameters(
- 'localhost')
- )
- # get channel
- channel = conn.channel()
- # declare queue, 重複聲明不會報錯,但是沒有隊列的話直接取用會報錯
- channel.queue_declare('hello')
- # get message
- channel.basic_consume(callback, queue='hello', no_ack=True)
- print ' [*] Waiting for messages. To exit press CTRL+C'
- channel.start_consuming()
- except Exception, e:
- raise e
- finally:
- if conn:
- conn.close()
現在:
1:在rabbitMQ安裝目錄的sbin下運行rabbitmq-server
2:在python文件目錄下運行:python hello_world_recv.py
3:在python文件目錄下運行:python hello_world_send.py
成功後可以看到
- $ python send_helloworld.py
- [x] Sent 'Hello World!'
- True
- $ python recv_helloworld.py
- [*] Waiting for messages. To exit press CTRL+C
- [x] Recived ch <pika.adapters.blocking_connection.BlockingChannel object at 0x7f61ecc6fa90>
- [x] Recived method <Basic.Deliver(['consumer_tag=ctag1.6c2c709930904468b40d0e1a758f7aca', 'delivery_tag=1', 'exchange=', 'redelivered=False', 'routing_key=hello'])>
- [x] Recived properties <BasicProperties>
- [x] Recived 'Hello, World!'
運行程序啓動後,一直在等待獲取消息,可以通過Ctrl-C來中止。Hello World基本就結束了,基本知道RabbitMQ基本的使用方法,後續將會進一步對RabbitMQ的使用場景進行解析。
下面給出一個參考網址:
https://blog.csdn.net/fgf00/article/details/52872730