rabbitmq篇---python拒收消息

channel.basic_reject(delivery_tag, requeue=True)

  • 功能: 拒绝单条消息
  • 参数:
    • delivery_tag : 传递标签
    • requeue=True : 是否重新放回到队列中去
channel.basic_reject()

具体代码如下

rabbit_utils.py

"""
创建拒收机制
"""
import pika
import json


def create_connection(config):
    """
    创建RabbitMQ连接
    :param config:
    :return:
    """
    # 功能: 创建连接时的登录凭证
    credentials = pika.PlainCredentials(username=config['username'], password=config['password'])  # mq用户名和密码
    # 虚拟队列需要指定参数 virtual_host,如果是默认的可以不填。
    # 功能: 连接 MQ 的参数设置
    param = pika.ConnectionParameters(host=config['host'], port=config['port'],
                                      virtual_host=config['virtual_host'], credentials=credentials)
    return pika.BlockingConnection(param)


class Subscriber():
    """
        消息订阅者
    """
    def __init__(self, queueName, bindingKey, config):
        self.queueName = queueName
        self.bindingKey = bindingKey
        self.config = config
        self.connection = create_connection(self.config)

    def __del__(self):
        self.connection.close()

    def setup(self, on_message_callback):
        # 功能:创建信道
        channel = self.connection.channel()
        # 功能:声明队列
        channel.queue_declare(queue=self.queueName, durable=True)
        # 功能:通过路由键将队列和交换器绑定
        channel.queue_bind(queue=self.queueName, exchange=self.config['exchange'], routing_key=self.bindingKey)
        # # 设置消费端处理完一条消息后再发另一条
        # channel.basic_qos(prefetch_count=1)
        # 功能:从队列中拿到消息开始消费
        channel.basic_consume(queue=self.queueName, on_message_callback=on_message_callback, auto_ack=False)
        try:
            channel.start_consuming()
        except KeyboardInterrupt:
            channel.stop_consuming()


class Publisher:
    """
        消息发布者
    """
    def __init__(self, queueName, config):
        self.queueName = queueName
        self.config = config

    def publish(self, routing_key, message):
        """
        :param routing_key:
        :param message:
        """
        connection = create_connection(self.config)
        channel = connection.channel()
        # channel.confirm_delivery()
        channel.queue_declare(queue=self.queueName, durable=True)
        # 从延迟队列获得消息
        channel.queue_bind(queue=self.queueName, exchange=self.config['exchange'], routing_key="source")
        channel.basic_publish(exchange=self.config['exchange'], routing_key=routing_key, body=message)
        print("[x] Sent message %r for %r" % (message, routing_key))

publisher.py

from utils.rabbit_utils import Publisher, Subscriber
import os
import time
import json


config = {'host': '127.0.0.1',
          'port': 5672,
          'username': 'ai.litter',
          'password': 'IRpNMSDHWq3hxLfv',
          'exchange': 'ai.litter',
          'virtual_host': 'slife',
          }


if __name__ == '__main__':
    sender = Publisher("ai.litter.source", config)

    i = 0
    while True:
        sender.publish("source", "hello world---{}".format(i))
        sender.publish("source", "world---{}".format(i))
        i += 1
        time.sleep(1)

consumer1.py

# -- coding: utf-8 --
from utils.rabbit_utils import Subscriber, Publisher


config = {'host': '127.0.0.1',
          'port': 5672,
          'username': 'ai.litter',
          'password': 'IRpNMSDHWq3hxLfv',
          'exchange': 'ai.litter',
          'virtual_host': 'slife',
          }


def on_message_callback(channel, method, properties, body):
    # 如果收到的消息是以hello开头的拒收
    if body.decode().startswith("hello"):
        # requeue True表示拒绝了消息后重新放回队列,False表示丢弃消息
        channel.basic_reject(delivery_tag=method.delivery_tag, requeue=True)
    message = body
    print(" [received] %r : %r" % (method.routing_key, message))


if __name__ == '__main__':
    receive = Subscriber('ai.litter.source', 'source', config)
    receive.setup(on_message_callback=on_message_callback)

consumer2.py

# -- coding: utf-8 --
from utils.rabbit_utils import Subscriber


config = {'host': '127.0.0.1',
          'port': 5672,
          'username': 'ai.litter',
          'password': 'IRpNMSDHWq3hxLfv',
          'exchange': 'ai.litter',
          'virtual_host': 'slife',
          }


def on_message_callback(channel, method, properties, body):
    # 如果收到的消息是以hello开头的拒收
    if body.decode().startswith("world"):
        # requeue True表示拒绝了消息后重新放回队列,False表示丢弃消息
        channel.basic_reject(delivery_tag=method.delivery_tag, requeue=True)
    message = body
    print(" [received] %r : %r" % (method.routing_key, message))


if __name__ == '__main__':
    receive = Subscriber('ai.litter.source', 'source', config)
    receive.setup(on_message_callback=on_message_callback)

结果展示

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

心惠天意

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值