1.生产者代码:
遇到的坑:
port不是15672,一定要是5672
15672是在虚拟机的网页上访问时输入的端口号,而5672才是链接时填的端口号
credentials = pika.PlainCredentials("test","test")里面的test一定是登录rabbitmq之后新创建的才可以,还要给这个账号设置权限
import pika
#创建一个可以登录rabbitmq服务的账号
credentials = pika.PlainCredentials("test","test")
#链接服务,输入虚拟机的ip和端口号以及账号信息
connection=pika.BlockingConnection(pika.ConnectionParameters(host='192.168.0.141',port=5672,credentials=credentials))
channel = connection.channel()#声明一个管道
#声明queue
channel.queue_declare(queue='hello')
#发送信息到hello这个队列中
channel.basic_publish(exchange='',routing_key='hello',body='hello world!!!')
print('[x] 发送‘hello world')
connection.close()
2.消费者代码:
遇到的坑:
我原先写成这样的
channel.basic_consume(callback, queue=‘celery’, no_ack=True)
结果报错
channel.basic_consume('hello',callback,False)
改成这样就可以了
import pika
credentials = pika.PlainCredentials("test","test")
connection=pika.BlockingConnection(pika.ConnectionParameters(host='192.168.0.141',port=5672,credentials=credentials))
channel = connection.channel()#声明一个管道
#声明queue
channel.queue_declare(queue='hello')
def callback(ch,method,properties,body):
print(ch,method,properties)
print('接受数据:%s'%body.decode())#如果传入的是汉字,需要decode一下,取回的信息才能正常显示汉字
channel.basic_consume('hello',callback,False)
print('[*] 等待信息,退出请按ctrl+c')
channel.start_consuming()