遵循模糊匹配原则
- 创建两个项目。分别为生产者和消费者。
引入JAR包依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2.生产者模式工程中,编写配置文件。
在topic主题中,只需要配置交换器,并不需要配置路由键,在direct模式主题中需要配置路由键,采取一对一的绑定规则。
spring.application.name=springcloud-mq
spring.rabbitmq.host=10.18.32.113
spring.rabbitmq.username=lzf
spring.rabbitmq.password=123456
spring.rabbitmq.port=5672
#设置交换器名称
mq.config.exchange= log.topic
- 在生产者类中,需要制定交换器的名称,以及注入AmqpTemplate的模板。
@Component
public class Order {
@Autowired
private AmqpTemplate amqpTemplate;
//exchange交换器名称
@Value("${mq.config.exchange}")
private String exchange;
//routingkey路由键名称
/* @Value("${mq.config.queue.error.routing.key}")
private String routingker;*/
/*
1.对下面这个方法的三个参数的说明
1.交换器的名称
2.路由键
3.消息
*/
public void send(String msg) {
this.amqpTemplate.convertAndSend(this.exchange, "order.log.debug", "product...debug========"+msg);
this.amqpTemplate.convertAndSend(this.exchange, "order.log.info", "order....info========"+msg);
this.amqpTemplate.convertAndSend(this.exchange, "order.log.warn", "order...warn========"+msg);
this.amqpTemplate.convertAndSend(this.exchange, "order.log.error", "order...error========"+msg);
}
}
4.配置消费者模式工程,需要在配置文件中设置交换器和和队列名称
以及一些基本的配置
spring.application.name=springcloud-mq
spring.rabbitmq.host=10.18.32.113
spring.rabbitmq.username=lzf
spring.rabbitmq.password=123456
spring.rabbitmq.port=5672
#设置交换器名称
mq.config.exchange=log.topic
#info队列名称
mq.config.queue.info=log.info
#error队列名称
mq.config.queue.error=log.error
#log队列的名称
mq.config.queue.log=log.all
5.在消费者类中进行建类
再类上加注解@RabbitListener,bindings:设置路由键绑定规则,进行队列消息的监听
@QueueBinding:中@Queue(value = "${mq.config.queue.info}"绑定队列名称
autoDelete="false"这个属性的意思是如果接收方服务器发生异常,导致没接受到消息,将不会反馈ACK消息,那么,队列会把消息重新再放到队列里,来保证队列消息不会丢失。
@Exchange(value = “${mq.config.exchange}”,type = ExchangeTypes.TOPIC),设置交换器名称和主题类型
key = "*.log.info"路由键的模糊匹配格式。
package com.qst.consumer;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;
@Component
@RabbitListener(
bindings = @QueueBinding(
value = @Queue(value = "${mq.config.queue.info}" ,autoDelete="false"),
exchange = @Exchange(value = "${mq.config.exchange}",type = ExchangeTypes.TOPIC),
key = "*.log.info"
)
)
public class InfoReceive {
@RabbitHandler
public void process(String msg){
System.out.println("Info ............receiver" +msg);
}
}