【问题标题】:Which one to use RabbitTemplate or AmqpTemplate?使用 RabbitTemplate 或 AmqpTemplate 哪一个?
【发布时间】:2017-08-25 05:50:58
【问题描述】:

我有以下用Spring Boot 编写的程序,它运行良好。但是,问题是我不确定我应该使用RabbitTemplate 还是AmqpTemplate。一些在线示例/教程使用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 !");
        }
    }

}

【问题讨论】:

    标签: spring spring-boot rabbitmq amqp spring-amqp


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      AmqpTemplate 是一个接口。 RabbitTemplate 是 AmqpTemplate 接口的实现。你应该使用 RabbitTemplate。

      【讨论】:

      • 您应该在此处说明为什么需要对实现进行编码,q.v。接受的答案。
      猜你喜欢
      • 2011-06-12
      • 2010-09-30
      • 2015-12-03
      • 2023-04-07
      • 2012-04-28
      • 1970-01-01
      • 1970-01-01
      • 2022-08-15
      • 1970-01-01
      相关资源
      最近更新 更多