sender1.py

1 # -*- coding:utf-8 -*-
2 # @Author:Liu Guoyang
3 # @Time :2019/8/7 21:14
4 # @File :sender1.py
5
6
7 import pika
8
9 credentials = pika.PlainCredentials('alex', 'alex123') # 服务端创建的用户名和密码
10 connection = pika.BlockingConnection(pika.ConnectionParameters(host="192.168.150.135", credentials=credentials))
11 # 建立了rabbit协议的通道
12 channel = connection.channel()
13
14 # 声明一个queue
15 channel.queue_declare(queue='hello')
16
17 # 发消息
18 channel.basic_publish(
19 exchange='',
20 routing_key='hello', # 把消息发给名称为hello的队列
21 body='Hello World!' # 发消息到队列,消息的内容
22 )
23
24 print("[x] Sent 'Hello World!'")
25 connection.close()
receive1.py

1 # -*- coding:utf-8 -*-
2 # @Author:Liu Guoyang
3 # @Time :2019/8/7 23:43
4 # @File :receive1.py
5
6 import pika
7 import time
8
9 credentials = pika.PlainCredentials('alex', 'alex123')
10 connection = pika.BlockingConnection(pika.ConnectionParameters(
11 '192.168.150.135', credentials=credentials))
12
13 channel = connection.channel()
14
15 # You may ask why we declare the queue again ‒ we have already declared it in our previous code.
16 # We could avoid that if we were sure that the queue already exists. For example if send.py program
17 # was run before. But we're not yet sure which program to run first. In such cases it's a good
18 # practice to repeat declaring the queue in both programs.
19 channel.queue_declare(queue='hello')
20
21
22 def callback(ch, method, properties, body):
23 print(" [x] Received %r" % body)
24
25
26 channel.basic_consume('hello', callback, False)
27
28 print(' [*] Waiting for messages. To exit press CTRL+C')
29 channel.start_consuming()
