javaspringspring-bootspring-amqpspring-rabbit

How to declare header exchange bindings in @RabbitListener annotation in with Spring AMQP?


I'm using Spring Boot 3.3 and I'd like to create a RabbitMQ listener using the @RabbitListener annotation. When binding to a topic exchange, I can easily specify the binding in the @RabbitListener itself like this:

@RabbitListener(
        id = "myRabbitListener",
        bindings = [QueueBinding(
                      value = Queue("myqueue"), 
                      exchange = Exchange(value = "mytopic-exchange", type = "topic"),
                      key = ["x", "y])])

I'd like to achieve a similar thing but for header exchanges, i.e. instead of specifying a routing key (using key) I'd like to specify which headers it should match, similar to declaring the binding like this:

@Bean
public Binding binding(Queue clientQueue, HeadersExchange headerExchange) {
    return BindingBuilder.bind(clientQueue).to(headerExchange)
            .where("tag1").matches("value1")
            .and("tag2").matches("value2");
}

Can you achieve this with the @RabbitListener annotation?


Solution

  • No, that is not possible with annotations. That headers matching logic is too hard to achieve with whatever we have so far with annotations API.

    It is really better to have such a binding declared as a regular bean via the mentioned BindingBuilder and then just use a plain queue reference in that @RabbitListener.