编程语言
首页 > 编程语言> > Java笔记-spring-rabbit框架中消息中header的添加

Java笔记-spring-rabbit框架中消息中header的添加

作者:互联网

对应的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 cn.it1995.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, "Hello.1111", 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);
    }

用管理工具查看下:

 

标签:rabbitTemplate,Java,spring,messageProperties,rabbitmq,header,new,Message
来源: https://blog.csdn.net/qq78442761/article/details/110495901