gpt4 book ai didi

java - 以静默方式将作业返回到队列

转载 作者:行者123 更新时间:2023-12-02 10:31:59 26 4
gpt4 key购买 nike

我有一个定义了作业队列的 RabbitMQ,并且我通过 Spring 框架使用 Java 来使用它。我知道,如果我在处理从队列收到的作业时在代码中的某个地方抛出异常,则会将作业返回到队列。但是,是否有其他方法可以将作业返回到队列,而不抛出异常或“手动”将作业返回到队列?

最佳答案

解决方案可能取决于您使用的抽象:

<小时/>

Spring 云流

我会使用Spring Cloud Stream Processor来做到这一点处理消息并设置 routingKeyExpression .

绑定(bind):

=> theSourceQueue 
=> myProcessor(message) consumes messages and setts routing key as a header
=> DestinationExchange
=> route 1 => theSourceQueue
=> route 2 => ?
<小时/>

Spring AMQP

import com.rabbitmq.client.Channel;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class Receiver {
@RabbitListener(queues = "my-messages")
public void receiveMessage(String payload, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {
System.out.println("Received message: `" + payload + "`, deliveryTag: " + deliveryTag);
channel.basicNack(deliveryTag, false, true);
}
}
<小时/>

RabbitMQ Java 客户端

你也可以到下层使用 negative acknowledgement and re-queue :

This example rejects two messages with a single call to the broker (the second argument on basicNack is the multiple flag):

GetResponse gr1 = channel.basicGet("some.queue", false);
GetResponse gr2 = channel.basicGet("some.queue", false);
channel.basicNack(gr2.getEnvelope().getDeliveryTag(), true, true);

When a message is requeued, it will be placed to its original position in its queue, if possible. If not (due to concurrent deliveries and acknowledgements from other consumers when multiple consumers share a queue), the message will be requeued to a position closer to queue head.

关于java - 以静默方式将作业返回到队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53565428/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com