RabbitMQ如何定时消费固定消息?

问题描述 投票:0回答:1

目前使用的是

spring-boot-starter-amqp
模块,可以使用注解
@RabbitListener
在后台读取消息,如何只在调用方法时从队列中消费固定数量的消息?

我要构建的是一个队列的“按需”消费者,我将在端点上收到一个包含消息数量的 HTTP 请求,我只想消费这个定义的数量。

java rabbitmq spring-rabbit
1个回答
0
投票

为此,您不得使用

@RabbitListener
,而是使用专用 API 进行按需接收。见
RabbitTemplate

/**
 * Receive a message if there is one from a default queue. Returns immediately,
 * possibly with a null value.
 *
 * @return a message or null if there is none waiting
 * @throws AmqpException if there is a problem
 */
@Nullable
Message receive() throws AmqpException;

要优化此批处理请求调用,您可以考虑使用作用域操作:

/**
 * Invoke the callback and run all operations on the template argument in a dedicated
 * thread-bound channel and reliably close the channel afterwards.
 * @param action the call back.
 * @param <T> the return type.
 * @return the result from the
 * {@link OperationsCallback#doInRabbit(RabbitOperations operations)}.
 * @throws AmqpException if one occurs.
 * @since 2.0
 */
@Nullable
default <T> T invoke(OperationsCallback<T> action) throws AmqpException {

在文档中查看更多信息:https://docs.spring.io/spring-amqp/reference/html/#amqp-template

© www.soinside.com 2019 - 2024. All rights reserved.