Putting it All Together

以下配置创建了交换 myDestination,其中队列 myDestination.consumerGroup 绑定到具有通配符路由键 # 的主题交换。

---
spring.cloud.stream.bindings.input.destination=myDestination
spring.cloud.stream.bindings.input.group=consumerGroup
#disable binder retries
spring.cloud.stream.bindings.input.consumer.max-attempts=1
#dlx/dlq setup
spring.cloud.stream.rabbit.bindings.input.consumer.auto-bind-dlq=true
spring.cloud.stream.rabbit.bindings.input.consumer.dlq-ttl=5000
spring.cloud.stream.rabbit.bindings.input.consumer.dlq-dead-letter-exchange=
---

此配置创建了一个名为 DLX 的死信队列,该队列使用 myDestination.consumerGroup 的路由键绑定到一个直连交换。当消息被拒绝时,它们将被路由到死信队列。5 秒后,该消息将过期,并使用队列名称作为路由键将其路由到原始队列,如下例所示:

Spring Boot application
@SpringBootApplication
public class XDeathApplication {

    public static void main(String[] args) {
        SpringApplication.run(XDeathApplication.class, args);
    }

    @Bean
    public Consumer<Message<String>> listen() {
        return message -> {
            Map<?,?> death = message.getHeaders().get("x-death");
            if (death != null && death.get("count").equals(3L)) {
                // giving up - don't send to DLX
                throw new ImmediateAcknowledgeAmqpException("Failed after 4 attempts");
            }
            throw new AmqpRejectAndDontRequeueException("failed");
        };
    }

}

请注意,x-death 标头中的计数属性是一个 Long