2017-08-25 1650 views
0

我有以下程序寫在Spring Boot這工作正常。但問題是,我不確定我是否應該使用RabbitTemplateAmqpTemplate。一些在線示例/教程使用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 !"); 
     } 
    } 

} 

回答

1

在大多數情況下,對於Spring bean,我會建議使用接口,以防Spring因爲任何原因創建JDK代理。這對於RabbitTemplate來說是不尋常的,所以使用哪一個並不重要。

在某些情況下,您可能需要RabbitTemplate上沒有出現在界面上的方法;這將是您需要使用它的另一種情況。

但是,一般來說,最佳做法是讓用戶代碼使用接口,以免對實現產生嚴重依賴。

0

AmqpTemplate是一個接口。 RabbitTemplate是AmqpTemplate接口的一個實現。你應該使用RabbitTemplate。

相關問題