Spring 使用RabbitTemplate或AmqpTemplate的是哪一个?
我用Spring 使用RabbitTemplate或AmqpTemplate的是哪一个?,spring,spring-boot,rabbitmq,amqp,spring-amqp,Spring,Spring Boot,Rabbitmq,Amqp,Spring Amqp,我用Spring Boot编写了以下程序,运行良好。但是,问题是,我不确定是应该使用RabbitTemplate还是amqpmetlate。一些在线示例/教程使用RabbitTemplate,而另一些使用amqpmetlate 请说明什么是最佳实践以及应该使用哪种实践 @SpringBootApplication public class BasicApplication { private static RabbitTemplate rabbitTemplate; priva
Spring Boot
编写了以下程序,运行良好。但是,问题是,我不确定是应该使用RabbitTemplate
还是amqpmetlate
。一些在线示例/教程使用RabbitTemplate
,而另一些使用amqpmetlate
请说明什么是最佳实践以及应该使用哪种实践
@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 !");
}
}
}
AmqpTemplate是一个接口。RabbitTemplate是AmqpTemplate接口的一个实现。您应该使用rabbitmplate。在大多数情况下,对于Springbean,我建议使用接口,以防Spring出于任何原因创建JDK代理。这对于
rabbitmplate
来说是不寻常的,所以使用哪一个并不重要
在某些情况下,您可能需要rabbitmplate
上没有出现在界面上的方法;这将是你需要使用它的另一种情况
不过,一般来说,最佳实践是让用户代码使用接口,这样您就不会对实现产生硬依赖。您应该在这里说明为什么需要对实现进行编码,q.v.这是公认的答案。