1.安装依赖
rabbitmq是使用erlang语言开发的,因此需要先安装erlang.
# 创建rlang.repo库
curl -s https://packagecloud.io/install/repositories/rabbitmq/erlang/script.rpm.sh | sudo bash
# 安装erlang socat
yum install erlang socat
2.安装rabbitmq-server
# 创建rabbitmq-server.repo库
curl -s https://packagecloud.io/install/repositories/rabbitmq/rabbitmq-server/script.rpm.sh | sudo bash
# 设置开机自启
chkconfig rabbitmq-server on
# 启动
systemctl start rabbitmq-server
# 启动后台管理
rabbitmq-plugins enable rabbitmq_management
# 添加用户
rabbitmqctl add_user xxx xxx # 用户 密码
登录
3.python使用rabbitmq
kombu连接rabbitmq实例:
producer.py
from kombu import Connection, Queue
MQ_URL = 'amqp://user:password@ip:port/'
def mq(key, body, key_timeout=None):
connection = Connection(MQ_URL)
channel = connection.Producer(serializer='json')
channel.publish(
body=body,
routing_key=key,
expiration=key_timeout
)
connection.release()
if __name__ == '__main__':
mq('Message_send', {'email': {'suc': 'rooihoiho'}})
consmer.py
from kombu import Connection, Queue
def rec(queue_name):
MQ_URL = 'amqp://zzh:password@10.201.143.217:5672/'
connection = Connection(MQ_URL)
while True:
with connection.Consumer(
queues=[Queue(queue_name, routing_key=queue_name)],
accept=['json'],
callbacks=[task_callbacks],
prefetch_count=1
):
connection.drain_events(timeout=30)
def task_callbacks(body, message):
print(body)
MQ_URL = 'amqp://user:password@ip:port/'
connection = Connection(MQ_URL)
channel = connection.Producer(serializer='json')
channel.publish(
body=body,
routing_key='ACCEPT',
expiration=None
)
connection.release()
return message.ack()
if __name__ == '__main__':
print(rec('Message_send'))