The Exchange switch and FanoutExchange switch both ignore the key.
He will match according to the headers parameter, and then send the message to the corresponding message queue.
There are two matching rules
- Where Any - The header information has at least one match
- Where All - The header information must match exactly.
Let's create the exchange and queue, and binding.
@Component
public class HeaderExchange {
@Bean
public Queue queue1(){
return new Queue("testHeaderQueue");
}
@Bean
public HeadersExchange createExchange(){
return new HeadersExchange("testHeaderExchange");
}
@Bean
public Binding bind1(){
HashMap<String, Object> header = new HashMap<>();
header.put("queue", "queue1");
header.put("bindType", "whereAll");
return BindingBuilder.bind(queue1()).to(createExchange()).whereAny(header).match();
}
}
Then send the message
@RequestMapping("send")
public String testHeaderExchange(String param){
MessageProperties messageProperties = new MessageProperties();
messageProperties.setContentType("text/plain");
messageProperties.setContentEncoding("utf-8");
messageProperties.setHeader("queue","queue1");
Message message = new Message(param.getBytes(), messageProperties);
rabbitTemplate.convertAndSend("testHeaderExchange",null,message);
return "发送成功";
}
Then there is the consumer code
@Component
public class TestHeader {
@RabbitListener(queues = "testHeaderQueue")
public void rest(String mes, Message message, Channel channel){
Map<String, Object> headers = message.getMessageProperties().getHeaders();
for (Map.Entry<String, Object> stringObjectEntry : headers.entrySet()) {
System.out.println("key---->"+stringObjectEntry.getKey());
System.out.println("value---->"+stringObjectEntry.getValue());
}
System.out.println("接收到的消息"+mes);
try {
channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
} catch (IOException e) {
e.printStackTrace();
}
}
}
We successfully received it here.
This article referring to this article