目录
2. 在 application.yml 中配置rabbitmq的 连接信息:
可见,消费者1 绑定交换机的路由键为 key = "hello.queue.1" ,因此消费了5条奇数类型的消息;
消费者2 绑定交换机的路由键为 key = "hello.queue.*" ,两种都可以匹配上,因此消费了所有消息;
1.先加入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2. 在 application.yml 中配置rabbitmq的 连接信息:
spring:
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
listener:
simple:
acknowledge-mode: manual
prefetch: 1
3.创建生产者
@Component
public class Sender {
@Autowired
private AmqpTemplate amqpTemplate;
public void sendTopicType(String msg,String key){
//参数:1-交换机 2-路由键 3-发送的信息
this.amqpTemplate.convertAndSend("hello.exchange.topic",key,msg);
}
}
4.创建两个消费者
第一个
@Slf4j
@Component
@RabbitListener(bindings = @QueueBinding(
//指定绑定的队列(该队列将自动创建),autoDelete="true"意味着程序关闭时该队列自动删除
value = @Queue(value = "hello.topic.queue-1",autoDelete = "true"),
//指定交换机,交换机类型:topic
exchange = @Exchange(value = "hello.exchange.topic",type = ExchangeTypes.TOPIC),
//队列与交换机绑定的路由键,带有此路由键的消息会被交换机发送到该队列
key = "hello.queue.1"
))
public class TopicReceiver1 {
@SneakyThrows
@RabbitHandler
public void process(String msg, Channel channel, Message message){
log.info("TopicReceiver1 = {}",msg);
channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
}
}
第二个
@Slf4j
@Component
@RabbitListener(bindings = @QueueBinding(
//指定绑定的队列(该队列将自动创建),autoDelete="true"意味着程序关闭时该队列自动删除
value = @Queue(value = "hello.topic.queue-2",autoDelete = "true"),
//指定交换机,交换机类型:topic
exchange = @Exchange(value = "hello.exchange.topic",type = ExchangeTypes.TOPIC),
//队列与交换机绑定的路由键,带有此路由键的消息会被交换机发送到该队列
//topic 模式可以使用通配符,* 代表几个单词,# 代表多个单词
key = "hello.queue.*"
))
public class TopicReceiver2 {
@SneakyThrows
@RabbitHandler
public void process(String msg, Channel channel, Message message){
log.info("TopicReceiver2 = {}",msg);
channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
}
}
5.测试类中测试
@SpringBootTest
class Rabbitmt1ApplicationTests {
@Autowired
private Sender sender;
@Test
void sendRoutingType() throws Exception{
for (int i=0; i<10; i++){
//奇数偶数不同,分别用两个路由键key
String key = i%2==0 ? "hello.queue.2":"hello.queue.1";
sender.sendRoutingType("hello-"+i,key);
}
}
}