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

用管理工具查看下:

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页