python中rabbitmq的简单使用--Windows

开始准备

首先需要安装rabbitmq和erlang,安装方式很简单

  • 其中需要注意的是版本问题 我暂时用的3.8.5和23.0
    https://www.rabbitmq.com/changelog.html
  • 还需要添加一下erlang
  • python中需要安装pika库

代码中的参数可能不一样,那是pika版本问题,0点几的版本和1点几的版本参数有所不同

send.py
生产者

import random
import pika

# credentials = pika.PlainCredentials("","")
# 新建连接,rabbitmq安装在本地则hostname为'localhost'
hostname = 'localhost'
parameters = pika.ConnectionParameters(hostname)
connection = pika.BlockingConnection(parameters)

# 创建通道
channel = connection.channel()

# 声明一个队列,生产者和消费者都要声明一个相同的队列, 用来防止万一某一方挂了,另一方能正常运行
channel.queue_declare(queue='hello') # durable=True队列持久化

number = random.randint(1, 1000)
body = 'hello world:%s' % number
# 交换机; 队列名,写明将消息发往哪个队列; 消息内容
# routing_key在使用匿名交换机的时候才需要指定,表示发送到哪个队列
channel.basic_publish(exchange="", routing_key="task_queue", body=message,
                      properties=pika.BasicProperties(delivery_mode=2   # 使消息持久化,
                                                      )
                      )
print(" [x] Sent %s" % body)
connection.close()

reveive.py
消费者

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
import pika

hostname = 'localhost'
parameters = pika.ConnectionParameters(hostname)
connection = pika.BlockingConnection(parameters)

# 创建通道
channel = connection.channel()
# channel.queue_declare(queue='hello')


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


# 告诉rabbitmq使用callback来接收信息
channel.basic_consume(queue="hello",on_message_callback=callback,auto_ack=True)

# 开始接收信息,并进入阻塞状态,队列里有信息才会调用callback进行处理,按ctrl+c退出
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

消费者中需要注意 channel.basic_consume中的auto_ack,用于是否需要确认
确认就是在callback中加一个 ch.basic_ack(delivery_tag=method.delivery_tag)

recv_safe.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time

import pika

hostname = 'localhost'
parameters = pika.ConnectionParameters(hostname)
connection = pika.BlockingConnection(parameters)

# 创建通道
channel = connection.channel()

channel.queue_declare(queue='hello') # durable=True队列持久化


def callback(ch, method, properties, body):
    time.sleep(10)
    print(" [x] Received %r" % (body,))
    ch.basic_ack(delivery_tag=method.delivery_tag)
    # ack 确认


# 告诉rabbitmq使用callback来接收信息
channel.basic_consume(queue="hello", on_message_callback=callback,
                      auto_ack=False)  # auto_ack  True生产者发出之后就不管了,不需要确认  False

# 开始接收信息,并进入阻塞状态,队列里有信息才会调用callback进行处理,按ctrl+c退出
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

队列持久化,需要在声明队列时将属性durable设置为True
消息持久化,需要将basic_publish中的properties属性设置pika.BasicProperties(delivery_mode=2 )

如果队列关闭,消息也会关闭

群发和组发
这段代码的运行方式是python 文件名称 + 参数
注释着的是群发

group_send.py

import sys

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters("localhost"))

channel = connection.channel()

# channel.exchange_declare(exchange="direct_logs", exchange_type="direct")
channel.exchange_declare(exchange="topic_logs", exchange_type="topic")
# 第一个值为级别
# severity = sys.argv[1] if len(sys.argv) > 1 else 'info'  # 严重程度
severity = sys.argv[1] if len(sys.argv) > 1 else 'anonymous.info'  # 严重程度   mysql.*
# 第二个值为消息
message = ' '.join(sys.argv[2:] or "Hello World!")
# channel.basic_publish(exchange="direct_logs", routing_key=severity, body=message.encode())
channel.basic_publish(exchange="topic_logs", routing_key=severity, body=message.encode())

connection.close()

group_recv

import sys

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
channel = connection.channel()

# channel.exchange_declare(exchange="direct_logs", exchange_type="direct")# direct类型
channel.exchange_declare(exchange="topic_logs", exchange_type="topic")# topic类型

result = channel.queue_declare(queue="", exclusive=True) # queue为空会随机给出一个唯一的名称
queue_name = result.method.queue

# 获取所有的参数
severities = sys.argv[1:]

if not severities:
    sys.stderr.write("sage:%s[info] [warning] [error]\n" % sys.argv[0])
    sys.exit(1)

# 循环进行绑定级别
for severity in severities:
    channel.queue_bind(exchange='topic_logs',
                       queue=queue_name,
                       routing_key=severity)

print(' [*] Waiting for logs. To exit press CTRL+C')

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


channel.basic_consume(on_message_callback=callback,
                      queue=queue_name,
                      auto_ack=True)

channel.start_consuming()

在这里插入图片描述

这个是在本地使用的,如果连接其他需要用户认证和一个类似白名单的,具体之后再加

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值