spring 无法使用与Sping Boot 的标头交换将消息发布到RabbitMQ

pkwftd7m  于 2022-12-02  发布在  Spring
关注(0)|答案(2)|浏览(149)

我有一个非常基本的Spring Boot应用程序,它使用headers交换将两条消息发布到RabbitMQexchangequeue都被创建,但是消息没有到达队列。我也没有看到任何异常。
我在谷歌上搜索了一下,但没有找到任何与此相关的例子。

基本应用程序.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();
    }

}

生成器.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 !");
    }

}
rt4zxlrg

rt4zxlrg1#

您所创建的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);
vuktfyat

vuktfyat2#

从Java 8开始,您还可以使用MessagePostProcessorCallback,如下所示:

this.rabbitTemplate.convertAndSend(EXCHANGE_NAME, "", "Hello World !", message -> {
     message.getMessageProperties().getHeaders().put("color", "gold");
     return message;
    });

相关问题