spring 消费者问题中的兔子异常

spring rabbit exception in consumer issue

我有一个spring兔子消费者:

public class SlackIdle1Consumer extends AbstractMessageConsumer {

    @Override public void process(Message amqpMessage, Channel channel)
            throws Exception {

    /*very bad exception goes here. 
it causes amqp message to be rejected and if no other consumer is available and error 
still persists, the message begins looping over and over.
And when the error is fixed,
those messages are being processed but the result of this procession may be harmful. 
     */

        }
    }
}

并且内部某处发生了异常。让我们想象这是一个糟糕的异常——开发逻辑错误。所以 amqp 消息开始无限期地旋转,当错误被修复并且消费者重新启动时,所有旧消息都在处理,这很糟糕,因为逻辑和数据可能会在这些消息发送后发生变化。如何正确处理?

所以问题是:如何正确解决这种情况?我应该将我的所有代码包装到 try-catch 子句中,还是我必须在每个消费者中开发 'checks' 以防止我的应用程序出现一致性问题?

有几种选择:

  1. 将容器的 defaultRequeueRejected 属性 设置为 false 所以失败的消息总是被拒绝(丢弃或发送到死信交换取决于 queue配置)。

  2. 如果你想重试一些异常而另一些不重试,那么添加一个 try catch 并抛出一个 AmqpRejectAndDontRequeueException 来拒绝那些你不想重试的异常。

  3. 向容器添加自定义 ErrorHandler,以执行与 #2 相同的操作 - 确定要重试的异常 - documentation here.

  4. 添加带有恢复器的重试建议 - 默认恢复器仅记录错误,RejectAndDontRequeueRecoverer 导致消息在重试耗尽后被拒绝,RepublishMessageRecoverer 是用于在 headers - documentation here.

  5. 中写入带有附加诊断的 queue