Spring Builders

Heiko Scherrer
Heiko Scherrer

Posted on • Updated on

TIL: Handle different Spring AMQP message types

Assume you have so far one single @RabbitListener that listens on a queue for messages. The restriction here is, that only one type is accepted by the listener method. Like this:

    @Measured
    @RabbitListener(queues = "${owms.commands.common.loc.queue-name}")
    public void onCommand(@Payload LocationCommand command) {
    ..
    }
Enter fullscreen mode Exit fullscreen mode

But if your listener accepts different types of messages, you can simply declare different handler methods and place the @RabbitListener annotation on top of the listening class:

@Component
@RabbitListener(queues = "${owms.events.common.loc.queue-name}")
class LocationMessageListener {

    @RabbitHandler
    public void onLocationEvent(@Payload LocationMO obj, @Header("amqp_receivedRoutingKey") String routingKey) {
    ...
    }

    @RabbitHandler
    public void onLocationEvent(@Payload RevokeLocationRemoveCommand obj, @Header("amqp_receivedRoutingKey") String routingKey) {
    ...
    }
}

Enter fullscreen mode Exit fullscreen mode

The @Component was required for me, since Spring didn't recognize the @RabbitListener as a bean.

Top comments (0)