2017-08-21 86 views
2

發佈扇出交換上的RabbitMQ消息,我有以下的代碼,使用fanout exchange發佈消息到RabbitMQ隊列。 exchange正在創建,但消息不能在RabbitMQ隊列中看到。我也沒有看到任何錯誤。如何使用Spring引導

BasicApplication.java

@SpringBootApplication 
public class BasicApplication { 

    public static final String QUEUE_NAME_1 = "helloworld.fanout.q1"; 
    public static final String QUEUE_NAME_2 = "helloworld.fanout.q2"; 
    public static final String EXCHANGE_NAME = "helloworld.fanout.x"; 

    //here the message ==> xchange ==> queue1, queue2 
    @Bean 
    public List<Declarable> fanoutBindings() { 
     Queue fanoutQueue1 = new Queue(QUEUE_NAME_1, false); 
     Queue fanoutQueue2 = new Queue(QUEUE_NAME_2, false); 
     FanoutExchange fanoutExchange = new FanoutExchange(EXCHANGE_NAME); 
     return Arrays.asList(
       fanoutQueue1, 
       fanoutQueue2, 
       fanoutExchange, 
       bind(fanoutQueue1).to(fanoutExchange), 
       BindingBuilder.bind(fanoutQueue2).to(fanoutExchange)); 
    } 

    public static void main(String[] args) { 
     SpringApplication.run(BasicApplication.class, args).close(); 
    } 

} 

Producer.java

@Component 
public class Producer implements CommandLineRunner { 

    @Autowired 
    private RabbitTemplate rabbitTemplate; 

    @Override 
    public void run(String... args) throws Exception { 
     this.rabbitTemplate.convertAndSend(EXCHANGE_NAME, "Hello World !"); 
    } 

} 

回答

3

您使用了錯誤的方法convertAndSend;該方法的第一個參數是routingKey

使用this.rabbitTemplate.convertAndSend(EXCHANGE_NAME, "", "Hello World !");

+0

良好,即工作:) – user2325154