pika python rabbitmq 优先级队列、查看队列剩余数目

话不多说,直接上代码。
python3.6 pika 实现rabbitmq 优先级队列

Send

import pika
import sys
import time



# 远程rabbitmq服务的配置信息
username = '用户名'  # 指定远程rabbitmq的用户名密码
pwd = '密码'
ip_addr = 'ip'
port_num = 5672

# 消息队列服务的连接和队列的创建
credentials = pika.PlainCredentials(username, pwd)
connection = pika.BlockingConnection(pika.ConnectionParameters(ip_addr, port_num, '/', credentials, heartbeat=0))
channel = connection.channel()
max_priority = 10
channel.queue_declare(queue='ws_interface_priority', arguments={"x-max-priority": max_priority}, durable=True)

for x in range(0,10000):
  
    channel.basic_publish(
        exchange='',
        routing_key='ws_interface_priority',  # 写明将消息发送给队列balance
        body=pub_dict,  # 要发送的消息
        properties=pika.BasicProperties(priority=1, delivery_mode=2, )  #priority=1,代表消息优先级,数字越大级别越高,可插队 设置消息持久化(持久化第二步),将要发送的消息的属性标记为2,表示该消息要持久化
    )  # 向消息队列发送一条消息
    print(" [%s] Sent 'message!'")
connection.close()  # 关闭消息队列服务的连接

consume

import pika
import json
import time
import os

# 远程rabbitmq服务的配置信息
username = '用户名'  # 指定远程rabbitmq的用户名密码
pwd = '密码'
ip_addr = 'ip'
port_num = 5672

credentials = pika.PlainCredentials(username, pwd)
connection = pika.BlockingConnection(pika.ConnectionParameters(ip_addr, port_num, '/', credentials, heartbeat=0))
connection.process_data_events()
channel = connection.channel()
max_priority = 10
channel.queue_declare(queue='ws_interface_priority', arguments={"x-max-priority": max_priority}, durable=True)


# 消费成功的回调函数
def callback(ch, method, properties, body):
    
    body = json.loads(body)
    id = (body["id"])
    。。。
    print(" [%s] Received %r" % (time.time(), body))
  
    # 具体逻辑

    # 当工作者完成任务后,会反馈给rabbitmq
    channel.basic_ack(delivery_tag=method.delivery_tag)


# 开始依次消费balance队列中的消息
channel.basic_qos(prefetch_count=1)
channel.basic_consume(on_message_callback=callback, queue='ws_interface_priority', auto_ack=False)

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

查看队列剩余数目

credentials = pika.PlainCredentials(username, pwd)
connection = pika.BlockingConnection(pika.ConnectionParameters(ip_addr_in, port_num, '/', credentials, heartbeat=0))
connection.process_data_events()
channel = connection.channel()
max_priority = 10
declear_queue_result = channel.queue_declare(queue=queue_name, arguments={"x-max-priority": max_priority}, durable=True)

queue_message_count = declear_queue_result.method.message_count

print(queue_message_count)
if queue_message_count == 0:
    # insert daily
    # do something. 
    # 这个代码略掉了一些 config 变量,自己定义一下
相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页