无法使用Spring Boot的头交换将消息发布到RabbitMQ上

时间:2017-08-21 21:49:13

标签: java spring spring-boot spring-rabbit spring-rabbitmq

我有一个非常基本的Spring Boot应用程序,它使用RabbitMQ交换将两条消息发布到headersexchangequeue都已创建,但邮件未到达队列。我也没有看到任何例外。

我用Google搜索,但找不到与此相关的任何示例。

BasicApplication.java

@SpringBootApplication
public class BasicApplication {

    public static final String QUEUE_NAME = "helloworld.header.red.q";
    public static final String EXCHANGE_NAME = "helloworld.header.x";

    //here the message ==> xchange ==> queue1, queue2
    @Bean
    public List<Object> headerBindings() {
        Queue headerRedQueue = new Queue(QUEUE_NAME, false);
        HeadersExchange headersExchange = new HeadersExchange(EXCHANGE_NAME);
        return Arrays.asList(headerRedQueue, headersExchange,
                bind(headerRedQueue).to(headersExchange).where("color").matches("red"));
    }

    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 {
        MessageProperties messageProperties = new MessageProperties();

        //send a message with "color: red" header in the queue, this will show up in the queue
        messageProperties.setHeader("color", "red");
        //MOST LIKELY THE PROBLEM IS HERE
        //BELOW MESSAGE IS NOT LINKED TO ABOVE messageProperties OBJECT
        this.rabbitTemplate.convertAndSend(EXCHANGE_NAME, "", "Hello World !");

        //send another message with "color: gold" header in the queue, this will NOT show up in the queue
        messageProperties.setHeader("color", "gold");
        this.rabbitTemplate.convertAndSend(EXCHANGE_NAME, "", "Hello World !");
    }

}

1 个答案:

答案 0 :(得分:2)

您已经更正了,因为您正在创建的MessageProperties未被使用。

尝试在Message的帮助下构建利用MessageProperties的{​​{1}}。

示例:

MessageConverter