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 !");
}
}
}
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.
AmqpTemplate is an interface. RabbitTemplate is an implementation of the AmqpTemplate interface. You should use RabbitTemplate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With