Java如何在spring-rabbit的消息中添加header信息呢?

戚薇 rabbitmq 发布时间:2023-06-09 21:22:58 阅读数:16061 1
下文笔者讲述spring-rabbit中消息里面添加header信息的方法及示例分享,如下所示

Spring-rabbit添加header信息的实现思路

1.定义一个 messageProperties 对象
2.添加头信息
    MessageProperties messageProperties = new MessageProperties();
        messageProperties.setHeader("key", "value1");
3.定义Message信息时,放入此MessageProperties
采用以上方式,即可在spring-rabbit上添加头信息
例:定义application.properties内容
spring.rabbitmq.host=122.xx.xxx.xxx
spring.rabbitmq.port=5672
spring.rabbitmq.username=xxxxxx
spring.rabbitmq.password=xxxxxx
spring.rabbitmq.virtual-host=/xxxxxx
spring.rabbitmq.cache.channel.checkout-timeout=10

示例代码

package com.java265.demo.component;
 
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.commandlinerunner;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
 
@Component
public class Runner implements CommandLineRunner {
    static final String topicExchangeName = "spring-head-test";
    static final String queueName = "spring-boot-head";
 
    @Bean
    Queue queue(){
        return new Queue(queueName, false);
    }
 
    @Bean
    TopicExchange exchange(){
        return new TopicExchange(topicExchangeName);
    }
 
    @Bean
    Binding binding(Queue queue, TopicExchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("Hello.*");
    }
 
    private final RabbitTemplate rabbitTemplate;
    public Runner(RabbitTemplate rabbitTemplate){
 
        this.rabbitTemplate = rabbitTemplate;
    }
 
    @Override
    public void run(String... args) throws Exception {
 
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setHeader("key", "value1");
 
        Message message = new Message("conduct oneself well".getBytes(), messageProperties);
        Message ret = rabbitTemplate.sendAndReceive(topicExchangeName, "this is java265", message);
        System.out.println(ret);
    }
}

设置头在run函数中

@Override
public void run(String... args) throws Exception {

	MessageProperties messageProperties = new MessageProperties();
	messageProperties.setHeader("key", "value1");

	Message message = new Message("conduct oneself well".getBytes(), messageProperties);
	Message ret = rabbitTemplate.sendAndReceive(topicExchangeName, "Hello.1111", message);
	System.out.println(ret);
} 
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/rabbitmq/2023/6759.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者