我目前有4个队列:


测试队列
测试队列短期死信
测试队列长期死信
测试队列停车场


当消息进入test-queue时,我进行检查以查看消息的格式是否正确。如果不是,我想直接将消息发送到停车场队列。

我不能使用AmqpRejectAndDontRequeue(),因为它会自动将消息发送到已配置的DLQ(test-queue-short-term-dead-letter)。

RabbitTemplate.convertAndSend()与另一个异常(例如BadRequestException)一起使用不起作用。该消息将按预期方式进入停车场队列,但是相同的消息将保留在test-queue

由于程序继续执行,因此单独使用RabbitTemplate.convertAndSend()无效。

所有队列都绑定到一个直接交换,每个交换都有唯一的路由密钥。 test-queue配置有以下参数:


x-dead-letter-exchange: ""
x-dead-letter-routing-key: <shortTermDeadLetterKey>


接收方:

  @RabbitListener(queues = "test-queue")
  public void receiveMessage(byte[] person) {
    String personString = new String(person);

    if (!personString.matches(desiredRegex)) {
      rabbitTemplate.convertAndSend("test-exchange", "test-queue-parking-lot",
          "invalid person");
      log.info("Invalid person");
    }
    ...some other code which I dont want to run as the message has arrived in the incorrect format
}

最佳答案

通过手动确认消息并从方法返回解决了该问题。

  @RabbitListener(queues = "test-queue")
  public void receiveMessage(byte[] person, Channel channel,
  @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws Exception) {
    String personString = new String(person);

    if (!personString.matches(desiredRegex)) {
      rabbitTemplate.convertAndSend("test-exchange", "test-queue-parking-lot",
          "invalid person");
      log.info("Invalid person");
      channel.basicAck(tag, false);
      return;
    }
    ...some other code which I dont want to run as the message has arrived in the incorrect format
}

07-26 06:17