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)
结果展示