1.rabbitmq是有erlang开发的,所以首先要先安装erlang
rpm -ivh erlang-18.1-1.el7.centos.x86_64.rpm
rpm -ivh rabbitmq-server-3.6.6-1.el7.noarch .rpm
安装rabbimq时提示依赖包socat未安装
yum -y install socat
安装完成后执行service rabbitmq-server start开启服务
2.使用python测试一下
python使用rabbitmq需要安装pika类库,我们可以使用pip安装pika,pip是python的软件管理包
安装pip
wget https://bootstrap.pypa.io/get-pip.py
python get-pip.py
安装pika
pip install pika
源代码参考原文http://blog.csdn.net/fgf00/article/details/52872730
创建send.py
#!/usr/bin/python
import pika # 建立一个实例
connection = pika.BlockingConnection( pika.ConnectionParameters('localhost',5672) # 默认端口5672,可不写 )
# 声明一个管道,在管道里发消息
channel = connection.channel()
# 在管道里声明queue
channel.queue_declare(queue='hello')
# 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='hello', # queue名字 body='Hello World!')
# 消息内容
print(" [x] Sent 'Hello World!'")
connection.close() # 队列关闭
创建receive.py
import pika
import time
# 建立实例
connection = pika.BlockingConnection(pika.ConnectionParameters( 'localhost'))
# 声明管道
channel = connection.channel()
# 为什么又声明了一个‘hello’队列? # 如果确定已经声明了,可以不声明。但是你不知道那个机器先运行,所以要声明两次。
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body): # 四个参数为标准格式
print(ch, method, properties) # 打印看一下是什么
# 管道内存对象 内容相关信息 后面讲
print(" [x] Received %r" % body)
time.sleep(15)
ch.basic_ack(delivery_tag = method.delivery_tag) # 告诉生成者,消息处理完成
channel.basic_consume( # 消费消息
callback, # 如果收到消息,就调用callback函数来处理消息
queue='hello', # 你要从那个队列里收消息
# no_ack=True # 写的话,如果接收消息,机器宕机消息就丢了 # 一般不写。宕机则生产者检测到发给其他消费者
)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming() # 开始消费消息
执行python send.py,输出
[x] Sent 'Hello World!'
执行rabbitmqctl list_queues,输出
Listing queues ...
hello 1
执行python receive.py,输出
[*] Waiting for messages. To exit press CTRL+C
(<pika.adapters.blocking_connection.BlockingChannel object at 0x1cbc510>, <Basic.Deliver(['consumer_tag=ctag1.bde4b3712fa64fccb5677c4fb420c35a', 'delivery_tag=1', 'exchange=', 'redelivered=False', 'routing_key=hello'])>, <BasicProperties>)
[x] Received 'Hello World!'