我的第一个rabbitMQ程序-hello_world

首先确定rabbitMQ已经安装完成,也就是在安装目录下运行rabbitMQ-server能成功

之后进行如下两个步骤:

首先创建一个hello_world_send.py

  1.   
  2. import os  
  3. import pika  
  4.   
  5. conn = None  
  6.   
  7. try:  
  8.     # 获取连接  
  9.     conn = pika.BlockingConnection(pika.ConnectionParameters('localhost'))  
  10.     # 获取通道  
  11.     channel = conn.channel()  
  12.   
  13.     # 在发送队列前,需要确定队列是否存在,如果不存在RabbitMQ将会丢弃,先创建队列  
  14.     channel.queue_declare('hello')  
  15.   
  16.     # 在RabbitMQ中发送消息,不是直接发送队列,而是发送交换机(exchange),此处不多做研究,后面系列逐渐深入  
  17.     ret = channel.basic_publish(exchange='',  
  18.                                 routing_key='hello',  
  19.                                 body="Hello, World!")  
  20.     print " [x] Sent 'Hello World!'"  
  21.     print ret  
  22. except Exception, e:  
  23.     raise e  
  24. finally:  
  25.     if conn:  
  26.         conn.close()

然后创建一个hello_world_recv.py

  1.  
  2. import os  
  3. import pika  
  4.   
  5. conn = None  
  6.   
  7.   
  8. def callback(ch, method, properties, body):  
  9.     """ 
  10.         out body 
  11.     """  
  12.     print " [x] Recived ch {0}".format(ch)  
  13.   
  14.     print " [x] Recived method {0}".format(method)  
  15.   
  16.     print " [x] Recived properties {0}".format(properties)  
  17.   
  18.     print " [x] Recived %r" % (body, )  
  19.   
  20. try:  
  21.     # get connection  
  22.     conn = pika.BlockingConnection(pika.ConnectionParameters(  
  23.         'localhost')  
  24.     )  
  25.   
  26.     # get channel  
  27.     channel = conn.channel()  
  28.   
  29.     # declare queue, 重复声明不会报错,但是没有队列的话直接取用会报错  
  30.     channel.queue_declare('hello')  
  31.   
  32.     # get message  
  33.     channel.basic_consume(callback, queue='hello', no_ack=True)  
  34.   
  35.     print ' [*] Waiting for messages. To exit press CTRL+C'  
  36.     channel.start_consuming()  
  37. except Exception, e:  
  38.     raise e  
  39. finally:  
  40.     if conn:  
  41.         conn.close() 

现在:

1:在rabbitMQ安装目录的sbin下运行rabbitmq-server

2:在python文件目录下运行:python hello_world_recv.py

3:在python文件目录下运行:python hello_world_send.py

成功后可以看到

扫描二维码关注公众号,回复: 136722 查看本文章

  1. $ python send_helloworld.py   
  2.  [x] Sent 'Hello World!'  
  3. True 
  1. $ python recv_helloworld.py   
  2.  [*] Waiting for messages. To exit press CTRL+C  
  3.  [x] Recived ch <pika.adapters.blocking_connection.BlockingChannel object at 0x7f61ecc6fa90>  
  4.  [x] Recived method <Basic.Deliver(['consumer_tag=ctag1.6c2c709930904468b40d0e1a758f7aca', 'delivery_tag=1', 'exchange=', 'redelivered=False', 'routing_key=hello'])>  
  5.  [x] Recived properties <BasicProperties>  
  6.  [x] Recived 'Hello, World!' 

运行程序启动后,一直在等待获取消息,可以通过Ctrl-C来中止。Hello World基本就结束了,基本知道RabbitMQ基本的使用方法,后续将会进一步对RabbitMQ的使用场景进行解析。

下面给出一个参考网址:

https://blog.csdn.net/fgf00/article/details/52872730

猜你喜欢

转载自blog.csdn.net/zp704393004/article/details/79984102