先安装erlang
rpm -Uvh http://www.rabbitmq.com/releases/erlang/erlang-18.1-1.el7.centos.x86_64.rpm
安装rabbitmq-server
rpm -Uvh http://www.rabbitmq.com/releases/rabbitmq-server/v3.5.6/rabbitmq-server-3.5.6-1.noarch.rpm
查看rabbitmq-server有没有安装成功,能查到说明安装成功了
rpm -qa|grep rabbitmq
开启rabbit-server
service rabbitmq-server start
关闭服务
service rabbitmq-server stop
查看rabbit-server当前状态
rabbitmqctl status
安装好后
rabbitmq list_queues显示当前的队列列表
远程连接rabbitmq server的话,需要配置权限
首先在rabbitmq server上创建一个用户
sudo rabbitmqctl add_user yu yuhaha
同时还要配置权限,允许从外面访问(下面的命令相当于创建了一个管理员)
sudo rabbitmqctl set_permissions -p / yu ".*" ".*" ".*"
producer.py
#!/usr/bin/env python
# coding:utf8
# author:Z time:2019/1/11
import pika #建立连接
#指定用户名
credentials=pika.PlainCredentials('yu','yuhaha')
parameters=pika.ConnectionParameters(host='192.168.1.103',credentials=credentials)
connection = pika.BlockingConnection(parameters)
channel = connection.channel()#队列连接通道 # 声明queue
channel.queue_declare(queue='hello2') # n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
channel.basic_publish(exchange='',#消息过滤,为空表示默认
routing_key='hello2',#路由,实际消息放到哪个队列由这个参数控制
body='Hello World!2')#消息内容
print(" [x] Sent 'Hello World!'")
connection.close()
执行两次程序后,再次执行命令rabbitmq list_queues
consumer.py
#!/usr/bin/env python
# coding:utf8
# author:Z time:2019/1/11
import pika credentials=pika.PlainCredentials('yu','yuhaha')
paramters=pika.ConnectionParameters(host='192.168.1.103',credentials=credentials)
connection = pika.BlockingConnection(paramters)
channel = connection.channel()#队列连接通道 def callback(ch, method, properties, body):#队列连接通道,请求方法,消息参数,消息内容
print(" [x] Received %r" % body) channel.basic_consume(callback,#取到消息后,调用callback函数
queue='hello',
no_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()#开始消费,阻塞模式,没消息一直等,有消息就收,收完了继续等,是处于永远运行的状态
运行consumer.py,成功取到两条消息