python使用消息队列RabbitMq(入门)

windows平台开发和使用

安装

  安装Erlang:https://pan.baidu.com/s/1QcZDaI205uaue7mMWh5cSA

  安装RabbitMQ:https://pan.baidu.com/s/1r1TFv3m2SO8YmBenHMw62w

  安装pika:pip install pika

配置

  1、激活 RabbitMQ's Management Plugin:

"C:\Program Files\RabbitMQ Server\rabbitmq_server-3.6.5\sbin\rabbitmq-plugins.bat" enable rabbitmq_management

  

  

  2、启动服务。请注意需要管理员身份才可以。

 

net stop RabbitMQ && net start RabbitMQ

 

  

  3、创建用户,密码,绑定角色

    查看已有用户及用户的角色:

rabbitmqctl.bat list_users

  

    新增用户:

rabbitmqctl.bat add_user 用户名 密码

  

    设置管理员身份:

rabbitmqctl.bat set_user_tags user administrator

  

   登录RabbitMQ,浏览器输入:

http://localhost:15672/

  

  设置账号

  

 

 

 

 可以看到

 

 那让我们开始python编码吧

import pika
credentials = pika.PlainCredentials('admin','123456')
connection = pika.BlockingConnection(pika.ConnectionParameters(
    '127.0.0.1',5672,'/',credentials))
channel = connection.channel()

# 声明queue
channel.queue_declare(queue='balance')
data = 'Hello World,my name is hardy!'
# n 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='balance',
                      body=data)
print(" [x] Sent '%s'"%data)
connection.close()
producer生产者
__author__ = 'Alex Li'
import pika

credentials = pika.PlainCredentials('admin','123456')
connection = pika.BlockingConnection(pika.ConnectionParameters(
    '127.0.0.1',5672,'/',credentials))
channel = connection.channel()

# You may ask why we declare the queue again ‒ we have already declared it in our previous code.
# We could avoid that if we were sure that the queue already exists. For example if send.py program
# was run before. But we're not yet sure which program to run first. In such cases it's a good
# practice to repeat declaring the queue in both programs.
channel.queue_declare(queue='balance')


def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)


channel.basic_consume(callback,
                      queue='balance',
                      no_ack=True)

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
consumer消费者

注意:admin和123456是账号和密码。

 

至此,基本结束了,让我们进入进阶消息队列吧!

 参考来源https://www.cnblogs.com/ericli-ericli/p/5902270.html

转载于:https://www.cnblogs.com/hardykay/p/10207941.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值