springboot配置rabbitmq(经典队列)

一、添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

二、队列和交换机配置(将durable设置成false,方便修改测试,重启rabbitmq-server服务可以直接清空交换机和队列)

1、生产者统一接口


import java.nio.charset.StandardCharsets;
import java.util.Map;

import org.pro.config.DirectConfig;
import org.pro.config.FanoutConfig;
import org.pro.config.HeadersConfig;
import org.pro.config.TopicConfig;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
* @author Administrator
*/
@RestController
public class RabbitmqController {

private RabbitTemplate rabbitTemplate;

@PostMapping("/direct")
public String direct(@RequestBody String data) {
MessageProperties properties = setProperties();
rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
rabbitTemplate.send(DirectConfig.DIRECT_EXCHANGE, DirectConfig.ROUTING_KEY,
new Message(data.getBytes(StandardCharsets.UTF_8), properties));
return "已加入队列";
}

@PostMapping("/fanout")
public String fanout(@RequestBody String data) {
MessageProperties properties = setProperties();
rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
rabbitTemplate.send(FanoutConfig.FANOUT_EXCHANGE, "",
new Message(data.getBytes(StandardCharsets.UTF_8), properties));
return "已加入队列";
}

@PostMapping("/topic")
public String topic(@RequestBody String data) {
MessageProperties properties = setProperties();
rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
// 配置的路由键 #可代表0或多个单词,*代表一个单词
// 可匹配到1,3
String data1 = data + "1";
rabbitTemplate.send(TopicConfig.TOPIC_EXCHANGE, "topic",
new Message(data1.getBytes(StandardCharsets.UTF_8), properties));

// 可匹配到3,4
String data2 = data + "2";
rabbitTemplate.send(TopicConfig.TOPIC_EXCHANGE, "my.topic",
new Message(data2.getBytes(StandardCharsets.UTF_8), properties));

// 可匹配到1,2
String data3 = data + "3";
rabbitTemplate.send(TopicConfig.TOPIC_EXCHANGE, "topic.test",
new Message(data3.getBytes(StandardCharsets.UTF_8), properties));

// 可匹配到1
String data4 = data + "4";
rabbitTemplate.send(TopicConfig.TOPIC_EXCHANGE, "topic.test.hello",
new Message(data4.getBytes(StandardCharsets.UTF_8), properties));

// 无匹配
String data5 = data + "4";
rabbitTemplate.send(TopicConfig.TOPIC_EXCHANGE, "my.topic.test",
new Message(data5.getBytes(StandardCharsets.UTF_8), properties));

// 无匹配
String data6 = "#" + data + "5";
rabbitTemplate.send(TopicConfig.TOPIC_EXCHANGE, "my.topic.test.hello",
new Message(data6.getBytes(StandardCharsets.UTF_8), properties));
return "已加入队列";
}

@PostMapping("/headers/all")
public String headersAll(@RequestBody String data) {
MessageProperties properties1 = setProperties();
rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
properties1.getHeaders().putAll(Map.of("header1", "value1"));
String data1 = data + "1";
// 可匹配到1
rabbitTemplate.send(HeadersConfig.HEADERS_EXCHANGE_ALL, "",
new Message(data1.getBytes(StandardCharsets.UTF_8), properties1));

MessageProperties properties2 = setProperties();
rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
properties2.getHeaders().putAll(Map.of("header2", "value2"));
String data2 = data + "2";
// 可匹配到2
rabbitTemplate.send(HeadersConfig.HEADERS_EXCHANGE_ALL, "",
new Message(data2.getBytes(StandardCharsets.UTF_8), properties2));

MessageProperties properties3 = setProperties();
rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
properties3.getHeaders().putAll(Map.of("header1", "value1", "header2", "value2"));
String data3 = data + "3";
// 可匹配到1,2,3
rabbitTemplate.send(HeadersConfig.HEADERS_EXCHANGE_ALL, "",
new Message(data3.getBytes(StandardCharsets.UTF_8), properties3));

MessageProperties properties4 = setProperties();
rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
properties4.getHeaders().putAll(Map.of("header1", "value1", "header3", "value3"));
String data4 = data + "4";
// 可匹配到1
rabbitTemplate.send(HeadersConfig.HEADERS_EXCHANGE_ALL, "",
new Message(data4.getBytes(StandardCharsets.UTF_8), properties4));
return "已加入队列";
}

@PostMapping("/headers/any")
public String headersAny(@RequestBody String data) {
MessageProperties properties1 = setProperties();
rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
properties1.getHeaders().putAll(Map.of("header3", "value3"));
String data1 = data + "1";
// 可匹配到1,3
rabbitTemplate.send(HeadersConfig.HEADERS_EXCHANGE_ANY, "",
new Message(data1.getBytes(StandardCharsets.UTF_8), properties1));

MessageProperties properties2 = setProperties();
rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
properties2.getHeaders().putAll(Map.of("header4", "value4"));
String data2 = data + "2";
// 可匹配到2,3
rabbitTemplate.send(HeadersConfig.HEADERS_EXCHANGE_ANY, "",
new Message(data2.getBytes(StandardCharsets.UTF_8), properties2));

MessageProperties properties3 = setProperties();
rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
properties3.getHeaders().putAll(Map.of("header3", "value3", "header4", "value4"));
String data3 = data + "3";
// 可匹配到1,2,3
rabbitTemplate.send(HeadersConfig.HEADERS_EXCHANGE_ANY, "",
new Message(data3.getBytes(StandardCharsets.UTF_8), properties3));

MessageProperties properties4 = setProperties();
rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
properties4.getHeaders().putAll(Map.of("header3", "value3", "header4", "value4", "header1", "value2"));
String data4 = data + "4";
// 可匹配到1,2,3
rabbitTemplate.send(HeadersConfig.HEADERS_EXCHANGE_ANY, "",
new Message(data4.getBytes(StandardCharsets.UTF_8), properties4));
return "已加入队列";
}

private MessageProperties setProperties() {
MessageProperties properties = new MessageProperties();
// 内容类型
properties.setContentType(MessageProperties.DEFAULT_CONTENT_TYPE);
// 消息优先级
properties.setPriority(5);
return properties;
}

@Autowired
public void setRabbitTemplate(RabbitTemplate rabbitTemplate) {
this.rabbitTemplate = rabbitTemplate;
}

}

 

2、direct 直连交换机,多个队列绑定相同的路由键,消息会发给每一个队列

交换机、队列的配置和绑定:

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Administrator
 */
@Configuration
public class DirectConfig {

    public static final String DIRECT_EXCHANGE = "direct_exchange";
    public static final String DIRECT_QUEUE1 = "direct_queue1";
    public static final String DIRECT_QUEUE2 = "direct_queue2";
    public static final String DIRECT_QUEUE3 = "direct_queue3";
    public static final String DIRECT_QUEUE4 = "direct_queue4";
    public static final String ROUTING_KEY = "direct_key";

    @Bean
    public DirectExchange setDirectExchange() {
        return new DirectExchange(DIRECT_EXCHANGE);
    }

    @Bean
    public Queue directQ1() {
        return new Queue(DIRECT_QUEUE1);
    }

    @Bean
    public Queue directQ2() {
        return new Queue(DIRECT_QUEUE2);
    }

    @Bean
    public Queue directQ3() {
        return new Queue(DIRECT_QUEUE3);
    }

    @Bean
    public Queue directQ4() {
        return new Queue(DIRECT_QUEUE4);
    }

    @Bean
    public Binding directB1() {
        return BindingBuilder.bind(directQ1()).to(setDirectExchange()).with(ROUTING_KEY);
    }

    @Bean
    public Binding directB2() {
        return BindingBuilder.bind(directQ2()).to(setDirectExchange()).with(ROUTING_KEY);
    }

    @Bean
    public Binding directB3() {
        return BindingBuilder.bind(directQ3()).to(setDirectExchange()).with(ROUTING_KEY);
    }

    @Bean
    public Binding directB4() {
        return BindingBuilder.bind(directQ4()).to(setDirectExchange()).with(ROUTING_KEY);
    }

}

消费者:


import java.util.Collections;

import org.pro.config.DirectConfig;
import org.pro.util.TransportConst;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson2.JSONObject;
import com.rabbitmq.client.Channel;

import io.swagger.annotations.ApiOperation;

/**
* @author Administrator
*/
@Component
public class DirectConsumer {

private RestTemplate restTemplate;

@ApiOperation(value = "消息接收方法",
notes = "org.springframework.amqp.core.Message接收字符串、数字类的简单消息,"
+ "org.springframework.messaging.Message接收对象类复杂消息")
@RabbitListener(queues = DirectConfig.DIRECT_QUEUE1)
public void receiveQ1(Message message1, org.springframework.messaging.Message message2, Channel channel) {
System.out.println("接收消息的队列方法=>receiveQ1,message->" + new String(message1.getBody()));
// commonHandle(message1);
}

@RabbitListener(queues = DirectConfig.DIRECT_QUEUE2)
public void receiveQ2(Message message) {
System.out.println("接收消息的队列方法=>receiveQ2,message->" + new String(message.getBody()));
// commonHandle(message);
}

@RabbitListener(queues = DirectConfig.DIRECT_QUEUE3)
public void receiveQ3(Message message) {
System.out.println("接收消息的队列方法=>receiveQ3,message->" + new String(message.getBody()));
// commonHandle(message);
}

@RabbitListener(queues = DirectConfig.DIRECT_QUEUE4)
public void receiveQ4(Message message) {
System.out.println("接收消息的队列方法=>receiveQ4,message->" + new String(message.getBody()));
// commonHandle(message);
}

private void commonHandle(Message message) {
// 解析message1中的信息
String data = new String(message.getBody());
JSONObject jsonObject = JSONObject.parseObject(data);
// 获取资源路径和传递方法
String url = jsonObject.getString(TransportConst.TRANSMISSION_URL);
String httpMethod = jsonObject.getString(TransportConst.TRANSMISSION_HTTP_METHOD);
// 构建消息主体
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEntity<String> httpEntity = new HttpEntity<>(data, httpHeaders);
// 调用接口
ResponseEntity<String> exchange =
restTemplate.exchange(url, HttpMethod.valueOf(httpMethod), httpEntity, String.class);
System.out.println(exchange.getBody());
}

@Autowired
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}

}

 结果,所有队列都接收到消息

 

3、扇形交换机,不考虑路由键,消息直接广播到所有绑定交换机的队列

交换机、队列的配置和绑定:

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Administrator
 */
@Configuration
public class FanoutConfig {

    public static final String FANOUT_EXCHANGE = "fanout_exchange";
    public static final String FANOUT_QUEUE1 = "fanout_queue1";
    public static final String FANOUT_QUEUE2 = "fanout_queue2";
    public static final String FANOUT_QUEUE3 = "fanout_queue3";
    public static final String FANOUT_QUEUE4 = "fanout_queue4";

    @Bean
    public FanoutExchange setFanoutExchange() {
        return new FanoutExchange(FANOUT_EXCHANGE, false, true);
    }

    @Bean
    public Queue fanoutQ1() {
        return new Queue(FANOUT_QUEUE1, false);
    }

    @Bean
    public Queue fanoutQ2() {
        return new Queue(FANOUT_QUEUE2, false);
    }

    @Bean
    public Queue fanoutQ3() {
        return new Queue(FANOUT_QUEUE3, false);
    }

    @Bean
    public Queue fanoutQ4() {
        return new Queue(FANOUT_QUEUE4, false);
    }

    @Bean
    public Binding fanoutB1() {
        return BindingBuilder.bind(fanoutQ1()).to(setFanoutExchange());
    }

    @Bean
    public Binding fanoutB2() {
        return BindingBuilder.bind(fanoutQ2()).to(setFanoutExchange());
    }

    @Bean
    public Binding fanoutB3() {
        return BindingBuilder.bind(fanoutQ3()).to(setFanoutExchange());
    }

    @Bean
    public Binding fanoutB4() {
        return BindingBuilder.bind(fanoutQ4()).to(setFanoutExchange());
    }

}

消费者:

import java.util.Collections;

import org.pro.config.FanoutConfig;
import org.pro.util.TransportConst;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson2.JSONObject;
import com.rabbitmq.client.Channel;

/**
 * @author Administrator
 */
@Component
public class FanoutConsumer {

    private RestTemplate restTemplate;

    @RabbitListener(queues = FanoutConfig.FANOUT_QUEUE1)
    public void receiveQ1(Message message1, org.springframework.messaging.Message message2, Channel channel) {
        System.out.println("接收消息的队列方法=>receiveQ1,message->" + new String(message1.getBody()));
        // commonHandle(message1);
    }

    @RabbitListener(queues = FanoutConfig.FANOUT_QUEUE2)
    public void receiveQ2(Message message) {
        System.out.println("接收消息的队列方法=>receiveQ2,message->" + new String(message.getBody()));
        // commonHandle(message);
    }

    @RabbitListener(queues = FanoutConfig.FANOUT_QUEUE3)
    public void receiveQ3(Message message) {
        System.out.println("接收消息的队列方法=>receiveQ3,message->" + new String(message.getBody()));
        // commonHandle(message);
    }

    @RabbitListener(queues = FanoutConfig.FANOUT_QUEUE4)
    public void receiveQ4(Message message) {
        System.out.println("接收消息的队列方法=>receiveQ4,message->" + new String(message.getBody()));
        // commonHandle(message);
    }

    private void commonHandle(Message message) {
        // 解析message1中的信息
        String data = new String(message.getBody());
        JSONObject jsonObject = JSONObject.parseObject(data);
        // 获取资源路径和传递方法
        String url = jsonObject.getString(TransportConst.TRANSMISSION_URL);
        String httpMethod = jsonObject.getString(TransportConst.TRANSMISSION_HTTP_METHOD);
        // 构建消息主体
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        HttpEntity<String> httpEntity = new HttpEntity<>(data, httpHeaders);
        // 调用接口
        ResponseEntity<String> exchange =
            restTemplate.exchange(url, HttpMethod.valueOf(httpMethod), httpEntity, String.class);
        System.out.println(exchange.getBody());
    }

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

}

结果:消息广播到每个绑定交换机的队列

 4、主题交换机,根据路由键的模式匹配规则将消息发送到队列

交换机、队列的配置和绑定:


import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
* @author Administrator
*/
@Configuration
public class TopicConfig {

public static final String TOPIC_EXCHANGE = "topic_exchange";
public static final String TOPIC_QUEUE1 = "topic_queue1";
public static final String TOPIC_QUEUE2 = "topic_queue2";
public static final String TOPIC_QUEUE3 = "topic_queue3";
public static final String TOPIC_QUEUE4 = "topic_queue4";
public static final String TOPIC_QUEUE5 = "topic_queue5";
public static final String TOPIC_ROUTING_KEY1 = "topic.#";
public static final String TOPIC_ROUTING_KEY2 = "topic.*";
public static final String TOPIC_ROUTING_KEY3 = "#.topic";
public static final String TOPIC_ROUTING_KEY4 = "*.topic";
public static final String TOPIC_ROUTING_KEY5 = "*.topic.hello";

@Bean
public TopicExchange setTopicExchange() {
return new TopicExchange(TOPIC_EXCHANGE, false, true);
}

@Bean
public Queue topicQ1() {
return new Queue(TOPIC_QUEUE1, false);
}

@Bean
public Queue topicQ2() {
return new Queue(TOPIC_QUEUE2, false);
}

@Bean
public Queue topicQ3() {
return new Queue(TOPIC_QUEUE3, false);
}

@Bean
public Queue topicQ4() {
return new Queue(TOPIC_QUEUE4, false);
}

@Bean
public Queue topicQ5() {
return new Queue(TOPIC_QUEUE5, false);
}

@Bean
public Binding topicB1() {
return BindingBuilder.bind(topicQ1()).to(setTopicExchange()).with(TOPIC_ROUTING_KEY1);
}

@Bean
public Binding topicB2() {
return BindingBuilder.bind(topicQ2()).to(setTopicExchange()).with(TOPIC_ROUTING_KEY2);
}

@Bean
public Binding topicB3() {
return BindingBuilder.bind(topicQ3()).to(setTopicExchange()).with(TOPIC_ROUTING_KEY3);
}

@Bean
public Binding topicB4() {
return BindingBuilder.bind(topicQ4()).to(setTopicExchange()).with(TOPIC_ROUTING_KEY4);
}

@Bean
public Binding topicB5() {
return BindingBuilder.bind(topicQ5()).to(setTopicExchange()).with(TOPIC_ROUTING_KEY5);
}

}

消费者:


import java.util.Collections;

import org.pro.config.TopicConfig;
import org.pro.util.TransportConst;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson2.JSONObject;
import com.rabbitmq.client.Channel;

/**
* @author Administrator
*/
@Component
public class TopicConsumer {

private RestTemplate restTemplate;

@RabbitListener(queues = TopicConfig.TOPIC_QUEUE1)
public void receiveQ1(Message message1, org.springframework.messaging.Message message2, Channel channel) {
System.out.println("接收消息的队列方法=>receiveQ1,message->" + new String(message1.getBody()));
// commonHandle(message1);
}

@RabbitListener(queues = TopicConfig.TOPIC_QUEUE2)
public void receiveQ2(Message message) {
System.out.println("接收消息的队列方法=>receiveQ2,message->" + new String(message.getBody()));
// commonHandle(message);
}

@RabbitListener(queues = TopicConfig.TOPIC_QUEUE3)
public void receiveQ3(Message message) {
System.out.println("接收消息的队列方法=>receiveQ3,message->" + new String(message.getBody()));
// commonHandle(message);
}

@RabbitListener(queues = TopicConfig.TOPIC_QUEUE4)
public void receiveQ4(Message message) {
System.out.println("接收消息的队列方法=>receiveQ4,message->" + new String(message.getBody()));
// commonHandle(message);
}

@RabbitListener(queues = TopicConfig.TOPIC_QUEUE5)
public void receiveQ5(Message message) {
System.out.println("接收消息的队列方法=>receiveQ5,message->" + new String(message.getBody()));
// commonHandle(message);
}

private void commonHandle(Message message) {
// 解析message1中的信息
String data = new String(message.getBody());
JSONObject jsonObject = JSONObject.parseObject(data);
// 获取资源路径和传递方法
String url = jsonObject.getString(TransportConst.TRANSMISSION_URL);
String httpMethod = jsonObject.getString(TransportConst.TRANSMISSION_HTTP_METHOD);
// 构建消息主体
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEntity<String> httpEntity = new HttpEntity<>(data, httpHeaders);
// 调用接口
ResponseEntity<String> exchange =
restTemplate.exchange(url, HttpMethod.valueOf(httpMethod), httpEntity, String.class);
System.out.println(exchange.getBody());
}

@Autowired
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}

}

结果:“.”是分隔符,“*”可匹配一个,“#”可匹配多个,路由键以消费者为主,即配置,生产者发送时会带路由键进行匹配,匹配的位置也有讲究,交换固定的单词位置匹配不到

 5、头部交换机,根据消息头部的属性而不是路由键来决定消息的路由

交换机、队列的配置和绑定:

import java.util.Map;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.HeadersExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Administrator
 */
@Configuration
public class HeadersConfig {

    public static final String HEADERS_EXCHANGE_ALL = "headers_exchange_all";
    public static final String HEADERS_QUEUE_ALL1 = "headers_queue_all1";
    public static final String HEADERS_QUEUE_ALL2 = "headers_queue_all2";
    public static final String HEADERS_QUEUE_ALL3 = "headers_queue_all3";
    public static final Map<String, Object> allMap1 = Map.of("header1", "value1");
    public static final Map<String, Object> allMap2 = Map.of("header2", "value2");
    public static final Map<String, Object> allMap3 = Map.of("header1", "value1", "header2", "value2");

    public static final String HEADERS_EXCHANGE_ANY = "headers_exchange_any";
    public static final String HEADERS_QUEUE_ANY1 = "headers_queue_any1";
    public static final String HEADERS_QUEUE_ANY2 = "headers_queue_any2";
    public static final String HEADERS_QUEUE_ANY3 = "headers_queue_any3";
    public static final Map<String, Object> anyMap1 = Map.of("header3", "value3");
    public static final Map<String, Object> anyMap2 = Map.of("header4", "value4");
    public static final Map<String, Object> anyMap3 = Map.of("header3", "value3", "header4", "value4");

    @Bean
    public HeadersExchange headersExchangeAll() {
        return new HeadersExchange(HEADERS_EXCHANGE_ALL, false, true);
    }

    @Bean
    public Queue headersAllQ1() {
        return new Queue(HEADERS_QUEUE_ALL1, false);
    }

    @Bean
    public Queue headersAllQ2() {
        return new Queue(HEADERS_QUEUE_ALL2, false);
    }

    @Bean
    public Queue headersAllQ3() {
        return new Queue(HEADERS_QUEUE_ALL3, false);
    }

    @Bean
    public Binding headersAllB1() {
        return BindingBuilder.bind(headersAllQ1()).to(headersExchangeAll()).whereAll(allMap1).match();
    }

    @Bean
    public Binding headersAllB2() {
        return BindingBuilder.bind(headersAllQ2()).to(headersExchangeAll()).whereAll(allMap2).match();
    }

    @Bean
    public Binding headersAllB3() {
        return BindingBuilder.bind(headersAllQ3()).to(headersExchangeAll()).whereAll(allMap3).match();
    }

    @Bean
    public HeadersExchange headersExchangeAny() {
        return new HeadersExchange(HEADERS_EXCHANGE_ANY, false, true);
    }

    @Bean
    public Queue headersAnyQ1() {
        return new Queue(HEADERS_QUEUE_ANY1, false);
    }

    @Bean
    public Queue headersAnyQ2() {
        return new Queue(HEADERS_QUEUE_ANY2, false);
    }

    @Bean
    public Queue headersAnyQ3() {
        return new Queue(HEADERS_QUEUE_ANY3, false);
    }

    @Bean
    public Binding headersAnyB1() {
        return BindingBuilder.bind(headersAnyQ1()).to(headersExchangeAny()).whereAny(anyMap1).match();
    }

    @Bean
    public Binding headersAnyB2() {
        return BindingBuilder.bind(headersAnyQ2()).to(headersExchangeAny()).whereAny(anyMap2).match();
    }

    @Bean
    public Binding headersAnyB3() {
        return BindingBuilder.bind(headersAnyQ3()).to(headersExchangeAny()).whereAny(anyMap3).match();
    }

}

 

 消费者:

import java.util.Collections;

import org.pro.config.HeadersConfig;
import org.pro.util.TransportConst;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson2.JSONObject;
import com.rabbitmq.client.Channel;

/**
 * @author Administrator
 */
@Component
public class HeadersConsumer {

    private RestTemplate restTemplate;

    @RabbitListener(queues = HeadersConfig.HEADERS_QUEUE_ALL1)
    public void receiveAllQ1(Message message1, org.springframework.messaging.Message message2, Channel channel) {
        System.out.println("接收消息的队列方法=>receiveAllQ1,message->" + new String(message1.getBody()));
        // commonHandle(message1);
    }

    @RabbitListener(queues = HeadersConfig.HEADERS_QUEUE_ALL2)
    public void receiveAllQ2(Message message) {
        System.out.println("接收消息的队列方法=>receiveAllQ2,message->" + new String(message.getBody()));
        // commonHandle(message);
    }

    @RabbitListener(queues = HeadersConfig.HEADERS_QUEUE_ALL3)
    public void receiveAllQ3(Message message) {
        System.out.println("接收消息的队列方法=>receiveAllQ3,message->" + new String(message.getBody()));
        // commonHandle(message);
    }

    @RabbitListener(queues = HeadersConfig.HEADERS_QUEUE_ANY1)
    public void receiveAnyQ1(Message message1, org.springframework.messaging.Message message2, Channel channel) {
        System.out.println("接收消息的队列方法=>receiveAnyQ1,message->" + new String(message1.getBody()));
        // commonHandle(message1);
    }

    @RabbitListener(queues = HeadersConfig.HEADERS_QUEUE_ANY2)
    public void receiveAnyQ2(Message message) {
        System.out.println("接收消息的队列方法=>receiveAnyQ2,message->" + new String(message.getBody()));
        // commonHandle(message);
    }

    @RabbitListener(queues = HeadersConfig.HEADERS_QUEUE_ANY3)
    public void receiveAnyQ3(Message message) {
        System.out.println("接收消息的队列方法=>receiveAnyQ3,message->" + new String(message.getBody()));
        // commonHandle(message);
    }

    private void commonHandle(Message message) {
        // 解析message1中的信息
        String data = new String(message.getBody());
        JSONObject jsonObject = JSONObject.parseObject(data);
        // 获取资源路径和传递方法
        String url = jsonObject.getString(TransportConst.TRANSMISSION_URL);
        String httpMethod = jsonObject.getString(TransportConst.TRANSMISSION_HTTP_METHOD);
        // 构建消息主体
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        HttpEntity<String> httpEntity = new HttpEntity<>(data, httpHeaders);
        // 调用接口
        ResponseEntity<String> exchange =
            restTemplate.exchange(url, HttpMethod.valueOf(httpMethod), httpEntity, String.class);
        System.out.println(exchange.getBody());
    }

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

}

结果:匹配头部以配置为主,all匹配所有才能接收到消息,可以比配置多,不能比配置少,any部分匹配,只要有一条匹配上就可以接收到消息

 

posted @ 2025-06-02 01:40  此时不卷何时卷  阅读(50)  评论(0)    收藏  举报