java - 无法使用 Spring Boot 进行 header 交换将消息发布到 RabbitMQ

标签 java spring spring-boot spring-rabbit

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

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

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

}

最佳答案

您是正确的,您正在创建的 MessageProperties 未被使用。

尝试在 MessageConverter 的帮助下构建一个利用 MessagePropertiesMessage

示例:

MessageProperties messageProperties = new MessageProperties();
messageProperties.setHeader("color", "red");
MessageConverter messageConverter = new SimpleMessageConverter();
Message message = messageConverter.toMessage("Hello World !", messageProperties);
rabbitTemplate.send("helloworld.header.x", "", message);

关于java - 无法使用 Spring Boot 进行 header 交换将消息发布到 RabbitMQ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45806035/

相关文章:

mysql - @Qualifier 不能在 Spring Boot 中使用多个 DataSource bean

java - 如何为数据库连接创建不同的类

java - 在 PDFBox 中,如何更改 PDRectangle 对象的原点 (0,0)?

java - 为什么在Java中使用byteBuffer将字符写入大文件时出现额外的字符 '^@'

java - Spring,如何在客户端决定服务应该使用哪个消费者?

java - 我必须关心 ThreadPoolExecutor 的关闭吗?

java - rabbitmq 抛出 AmqpException : No method found for class [B

java - 错误 : cannot find symbol IOUtils. 复制(输入,输出);

java - 如何更改屏幕,以便当您单击屏幕上的任意位置时,您可以从问题转到答案?

java - Spring Boot 中预定义的 bean