Search code examples
springspring-bootrabbitmqamqpspring-amqp

Which one to use RabbitTemplate or AmqpTemplate?


I have the following program written in Spring Boot which is working fine. However, the problem is that the I am not sure whether I should be using RabbitTemplate or AmqpTemplate. Some of the online examples/tutorials use RabbitTemplate while others use AmqpTemplate.

Please guide as to what is the best practice and which one should be used.

@SpringBootApplication
public class BasicApplication {

    private static RabbitTemplate rabbitTemplate;
    private static final String QUEUE_NAME = "helloworld.q";

    //this definition of Queue is required in RabbitMQ. Not required in ActiveMQ
    @Bean
    public Queue queue() {
        return new Queue(QUEUE_NAME, false);
    }

    public static void main(String[] args) {
        try (ConfigurableApplicationContext ctx = SpringApplication.run(BasicApplication.class, args)) {
            rabbitTemplate = ctx.getBean(RabbitTemplate.class);
            rabbitTemplate.convertAndSend(QUEUE_NAME, "Hello World !");
        }
    }

}

Solution

  • In most cases, for Spring beans, I would advise using the interface, in case Spring creates a JDK proxy for any reason. That would be unusual for the RabbitTemplate so it doesn't really matter which you use.

    In some cases, you might need methods on the RabbitTemplate that don't appear on the interface; which would be another case where you would need to use it.

    In general, though, best practice is for user code to use interfaces so you don't have hard dependencies on implementations.