如何在RabbitMQ上每次使用固定消息?

o2gm4chl  于 2023-03-08  发布在  RabbitMQ
关注(0)|答案(1)|浏览(136)

目前,我正在使用spring-boot-starter-amqp模块,并且可以使用注解@RabbitListener在后台读取消息。如何仅在调用方法时从队列中消耗固定数量的消息?
我尝试构建的是队列的“按需”消费者,我将在端点上接收具有消息数量的HTTP请求,并且我只想消费定义的数量。

20jt8wwn

20jt8wwn1#

为此,您不能使用@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

相关问题