First make sure that rabbitMQ has been installed, that is, running rabbitMQ-server in the installation directory can be successful
Then do the following two steps:
First create a hello_world_send.py
- import them
- import pika
- conn = None
- try:
- # get connection
- conn = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
- # get channel
- channel = conn.channel()
- # Before sending the queue, you need to determine whether the queue exists. If it does not exist, RabbitMQ will discard it. Create the queue first.
- channel.queue_declare('hello')
- # Sending messages in RabbitMQ is not a direct queue, but an exchange. I won't do much research here, and the following series will gradually deepen
- ret = channel.basic_publish(exchange='',
- routing_key='hello',
- body="Hello, World!")
- print" [x] Sent 'Hello World!'"
- print right
- except Exception, e:
- raise e
- finally:
- if conn:
- conn.close()
Then create a hello_world_recv.py
-
- import them
- 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, repeated declaration will not report an error, but if there is no queue, direct access will report an error
- 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()
Now:
1: Run rabbitmq-server under sbin in the rabbitMQ installation directory
2: Run in the python file directory: python hello_world_recv.py
3: Run in the python file directory: python hello_world_send.py
After success you can see
- $ 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!'
After the running program starts, it has been waiting to get the message, which can be aborted by Ctrl-C. Hello World is basically over, you basically know the basic usage of RabbitMQ, and the usage scenarios of RabbitMQ will be further analyzed in the future.
A reference URL is given below:
https://blog.csdn.net/fgf00/article/details/52872730