centos7安装rabbitmq并简单使用

先安装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

centos7安装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

 1 #!/usr/bin/env python
 2 # coding:utf8
 3 # author:Z time:2019/1/11
 4 import pika
 5 
 6 #建立连接
 7 #指定用户名
 8 credentials=pika.PlainCredentials('yu','yuhaha')
 9 parameters=pika.ConnectionParameters(host='192.168.1.103',credentials=credentials)
10 connection = pika.BlockingConnection(parameters)
11 channel = connection.channel()#队列连接通道
12 
13 # 声明queue
14 channel.queue_declare(queue='hello2')
15 
16 # n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
17 channel.basic_publish(exchange='',#消息过滤,为空表示默认
18                       routing_key='hello2',#路由,实际消息放到哪个队列由这个参数控制
19                       body='Hello World!2')#消息内容
20 print(" [x] Sent 'Hello World!'")
21 connection.close()

执行两次程序后,再次执行命令rabbitmq list_queues

centos7安装rabbitmq并简单使用

 

 

consumer.py

 1 #!/usr/bin/env python
 2 # coding:utf8
 3 # author:Z time:2019/1/11
 4 import pika
 5 
 6 credentials=pika.PlainCredentials('yu','yuhaha')
 7 paramters=pika.ConnectionParameters(host='192.168.1.103',credentials=credentials)
 8 connection = pika.BlockingConnection(paramters)
 9 channel = connection.channel()#队列连接通道
10 
11 
12 def callback(ch, method, properties, body):#队列连接通道,请求方法,消息参数,消息内容
13     print(" [x] Received %r" % body)
14 
15 
16 channel.basic_consume(callback,#取到消息后,调用callback函数
17                       queue='hello',
18                       no_ack=True)
19 
20 print(' [*] Waiting for messages. To exit press CTRL+C')
21 channel.start_consuming()#开始消费,阻塞模式,没消息一直等,有消息就收,收完了继续等,是处于永远运行的状态

 运行consumer.py,成功取到两条消息

centos7安装rabbitmq并简单使用

 

上一篇:rabbitmq远程消费者生产者发送端接收端实例


下一篇:java-Google视觉API从文件加载凭据