码迷,mamicode.com
首页 > 编程语言 > 详细

RabbitMQ的安装和使用Python连接RabbitMQ

时间:2018-05-22 16:40:14      阅读:550      评论:0      收藏:0      [点我收藏+]

标签:rabbitmq   dmi   password   queue   callback   close   2.7   一个   back   

绪论


这里的环境使用的是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   dmi   password   queue   callback   close   2.7   一个   back   

原文地址:https://www.cnblogs.com/KevinGeorge/p/9072632.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!