使用 RabbitTemplate 或 AmqpTemplate 中的哪一个?

Nit*_*tal 4 spring amqp rabbitmq spring-amqp spring-boot

我编写了以下程序,Spring Boot该程序运行良好。但是,问题是我不确定我是否应该使用RabbitTemplateAmqpTemplate. 一些在线示例/教程使用,RabbitTemplate而另一些使用AmqpTemplate.

请指导什么是最佳实践以及应该使用哪一个。

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

}
Run Code Online (Sandbox Code Playgroud)

Gar*_*ell 5

在大多数情况下,对于 Spring bean,我建议使用该接口,以防 Spring 由于任何原因创建 JDK 代理。这对 来说是不寻常的,RabbitTemplate所以你使用哪个并不重要。

在某些情况下,您可能需要RabbitTemplate未出现在界面上的方法;这将是您需要使用它的另一种情况。

不过,一般来说,最佳实践是让用户代码使用接口,这样您就不会对实现有硬依赖。