概要:
主题交换机,所有符合的routingkey都可以匹配。这种模式下的routingkey必须是由点分开的一串单词。可以由多个单词,但是有最大限制。最大限制是:255bytes。
匹配规则:
*:表示匹配任意一个单词
#:表示匹配任意一个或多个单词。
application.properties配置:
spring.rabbitmq.host=localhost
# TCP/IP端口为5672,http端口为15672
spring.rabbitmq.port=5672
spring.rabbitmq.username=root
spring.rabbitmq.password=root
生产者:
package com.example.rabbitmq;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RabbitMQController {
// 这里用的是RabbitTemplate发消息,也可以用AmqpTemplate,推荐使用RabbitTemplate。
@Autowired
private RabbitTemplate rabbitTemplate;
@GetMapping(value = "/helloRabbit4")
public String sendMQ4(){
rabbitTemplate.convertAndSend("myExchange3", "routingKey.a.b","topicExchange");
rabbitTemplate.convertAndSend("myExchange3", "routingKey","topicExchange");
rabbitTemplate.convertAndSend("myExchange3", "routingKey.1","topicExchange");
return "success";
}
}
消费者:
package com.example.rabbitmq;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;
@Component
public class Receiver {
@RabbitListener(
bindings = @QueueBinding(
value = @Queue(value = "myQueue5"),
exchange = @Exchange(value = "myExchange3", type =ExchangeTypes.TOPIC),
key = "routingKey.#"
)
)
public void process5(Message message){
System.out.println("myQueue5:" + new String(message.getBody()));
}
启动项目,访问http://localhost:8080/helloRabbit3,控制台打印
myQueue5:topicExchange
myQueue5:topicExchange
myQueue5:topicExchange