rabbitmq之消息的异步确认

ConcurrentSkipListMap 和 channel.getNextPublishSeqNo()

channel.getNextPublishSeqNo可以获取发布的消息的下一个序号,有序递增。ConcurrentSkipListMap有一个heapMap方法,可以返回key小于等于param的map子集。在发布消息之前先获取序号,作为key放到map里面。

map.put(nextPublishSeqNo, byteMsg);
channel.basicPublish("", queueName, null, msgStr.substring(i, i + 1).getBytes(StandardCharsets.UTF_8));

异步确认

Producer只管发消息,然后注册一个异步回调函数。rabbitmq提供了两个回调函数。一个是发送成功的回调,一个是发送失败的回调。两个函数的参数是一样的,两个。

  • sequence number 序号。表示成功/失败的消息编号
  • multiple 布尔值。false表示只有一个被确认。true表示小于等于当前序号的消息发送成功/失败
channel.confirmSelect();//启用消息确认
channel.addConfirmListener(
        (deliveryTag, multiple) -> {
            if (multiple) {
                System.out.println("序号" + deliveryTag + "的信息发送成功");
                map.remove(deliveryTag);
            } else {
                System.out.println("序号小于" + deliveryTag + "的信息发送成功");
                final ConcurrentNavigableMap<Long, Byte> confirmed = map.headMap(deliveryTag, true);
                confirmed.clear();
            }
        },
        (deliveryTag, multiple) -> {
            if (!multiple) {
                System.out.println("发送失败的信息sequence number:" + deliveryTag);
            } else {
                System.out.println("序号小于" + deliveryTag + "的消息发送失败");
            }
        });

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在Python中集成RabbitMQ和FastAPI来实现异步消费消息,可以使用aio_pika库。 首先需要安装aio_pika和FastAPI: ``` pip install aio_pika fastapi ``` 然后可以使用以下代码作为示例: ```python from fastapi import FastAPI import aio_pika app = FastAPI() @app.on_event("startup") async def startup(): # 连接RabbitMQ connection = await aio_pika.connect_robust("amqp://guest:guest@localhost/") app.state.rabbitmq = connection @app.on_event("shutdown") async def shutdown(): # 关闭RabbitMQ连接 await app.state.rabbitmq.close() @app.get("/") async def read_root(): # 创建一个channel channel = await app.state.rabbitmq.channel() # 声明一个queue queue = await channel.declare_queue("my_queue") # 异步获取消息 async with queue.iterator() as queue_iter: async for message in queue_iter: async with message.process(): print(message.body) return {"status": "ok"} ``` 在上面的示例中,我们在FastAPI的startup事件中连接到RabbitMQ,并将连接保存在app.state.rabbitmq中。在shutdown事件中关闭连接。 在read_root函数中,我们创建一个channel并声明一个queue。然后使用queue.iterator()方法获取一个异步迭代器,并使用async for循环异步获取消息。在异步获取到消息后,我们使用message.process()方法来确认消息已经被处理。 当然,在实际应用中,你可能需要根据具体的业务场景来编写更加复杂的代码。不过,以上代码可以作为一个很好的起点来帮助你快速集成RabbitMQ和FastAPI。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值