centos7安装rabbitmq及python调用接口

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'))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值