RabbitMQ的安装和使用Python连接RabbitMQ

Posted 挖洞的土拨鼠

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RabbitMQ的安装和使用Python连接RabbitMQ相关的知识,希望对你有一定的参考价值。

绪论


这里的环境使用的是Mac OS X系统,所有的配置和使用都是基于Mac OS X 和Python 2.7 以及对应的pika库的。

RabbitMQ的安装和配置


安装部分

#brew install rabbitmq

配置和启动

#sudo brew services start rabbitmq
#sudo rabbitmqctl add_user admin admin                                   "创建用户(username  password)"
#sudo rabbitmqctl set_user_tags admin administrator                  "配置用户为超级管理员"
#sudo rabbitmqctl  set_permissions  -p  ‘/‘  admin ‘.‘ ‘.‘ ‘.‘            " 配置权限"
#sudo brew services restart rabbitmq                             

Python 与 pika


安装pika

#sudo pip install pika

Python与RabbitMQ的配合(基础)

# -*- coding:utf-8 -*-

import pika

class RabbitMQ(object):
    """一个简单的RabbitMQ的库,为了学习"""
    def __init__(self,host,port=5672,username=None,password=None):

        if host == None:
            raise Exception("Host is None")
        if username != None and password != None:
            try:
                self.Credentials = pika.PlainCredentials(username,password)
                self.ConnectionKeys = pika.ConnectionParameters(host,port,‘/‘,self.Credentials)
            except Exception:
                raise
        else:
            self.ConnectionKeys = None
    def _connection(self):
        try:
            if self.ConnectionKeys == None:
                self.connection = pika.BlockingConnection()
            else:
                self.connection = pika.BlockingConnection(self.ConnectionKeys)
        except Exception:
            raise
    def _channel(self):
        self.channel = self.connection.channel()
    def _callback(channel,method,properties,body):
        return body
    def connect(self):
        self._connection()
        self._channel()
    def create_queque(slef,flag,durableflag=False):
        try:
            self.channel.queue_declare(queue=flag,durable=durableflag)
        except Exception:
            raise
    def product(self,flag,content,exchange=‘‘):
        try:
            self.channel.basic_publish(exchange=‘‘,routing_key=flag,body=content)
        except Exception:
            raise
    def consume(slef,flag,ackflag):
        try:
            self.channel.basic_consume(self._callback,queue=flag,no_ack=ackflag)
        except Exception:
            raise
    def close(self):
        try:
            self.connection.close()
        except Exception:
            raise

以上是关于RabbitMQ的安装和使用Python连接RabbitMQ的主要内容,如果未能解决你的问题,请参考以下文章

RabbitMQ 消息队列学习

Linux下安装RabbitMQ

RabbitMQ安装

Windows系统下安装RabbitMQ

Docker下安装RabbitMQ镜像

私有云Rabbitmq 集群部署