Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !");
        }
    }

}
like image 773
Nital Avatar asked Mar 09 '23 05:03

Nital


2 Answers

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.

like image 151
Gary Russell Avatar answered Mar 16 '23 03:03

Gary Russell


AmqpTemplate is an interface. RabbitTemplate is an implementation of the AmqpTemplate interface. You should use RabbitTemplate.

like image 34
yamenk Avatar answered Mar 16 '23 03:03

yamenk