Search code examples
javaspringspring-bootrabbitmqspring-rabbit

Use @SentTo to send a message with Spring Boot and RabbitMq


Is it possible to send a return value of any method to a queue using an annotation, like

@SentTo("my.queue.name")
String send() {
    return myString;
}

Do I definitely need a @RabbitListener to use @SendTo? Maybe another way out?

I'm trying to simplify my code.


Solution

  • @SendTo is only currently for replies from a @RabbitListener where the sender didn't set a replyTo header.

    You could do what you want with a Spring Integration @Publisher annotation with its channel wired to a rabbitmq outbound channel adapter...

    @Publisher(channel = "amqpOutboundChannel")
    public String send() {
        return myString;
    }
    
    @Bean
    @ServiceActivator(inputChannel = "amqpOutboundChannel")
    public AmqpOutboundEndpoint amqpOutbound(AmqpTemplate amqpTemplate) {
        AmqpOutboundEndpoint outbound = new AmqpOutboundEndpoint(amqpTemplate);
        outbound.setRoutingKey("my.queue.name"); // default exchange - route to queue 'my.queue.name'
        return outbound;
    }
    

    The method has to be public and invoked from outside the bean itself.