一、topic交换器为主题交换器,可以根据路由key模糊匹配
实现模型图
二、实战
1、引入maven
<dependency> <groupId>org.springframework.amqp</groupId> <artifactId>spring-rabbit</artifactId> </dependency>
2、修改配置文件
server:
port: 8080
servlet:
context-path: /rabbitmq
spring:
application:
#指定应用的名字
name: rabbit-add
#配置rabbitmq
rabbitmq:
#链接主机
host: 127.0.0.1
#端口
port: 5672
#已经授权的用户账号密码
username: user
password: user
#指定的虚拟主机,默认/,
virtual-host: my_vhost
# 自定义配置应用于topic交换器
mq:
config:
#自定义交换器名称
exchange: log.topic
queue:
#自定义error、info、all队列名称
errorName: topic.error.log
infoName: topic.info.log
allName: topic.all.log
#自定义error、info、all路由键的名称
routingInfoKey: topic.info.routing.key
routingErrorKey: topic.error.routing.key
3、消费者代码
a、模糊匹配所有的数据队列,注意在配置路由key的时候是*代表阶段的配置,.不在匹配范围内
package com.niu.topic; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.core.ExchangeTypes; import org.springframework.amqp.rabbit.annotation.*; import org.springframework.stereotype.Component; /** * @author niunafei * @function * @email niunafei0315@163.com * @date 2020/4/28 7:20 PM * @RabbitListener 自定义监听事件 * @QueueBinding 绑定交换器与队列的关系value 指定队列exchange指定交换器 * value= @Queue 指定配置队列的信息 value队列名称 autoDelete是否是临时队列 * exchange= @Exchange 指定交换器 value指定交换器名称 type交换器类型 * key 指定路由键 */ @Component @Slf4j @RabbitListener( bindings = @QueueBinding( value = @Queue( value = "${mq.config.queue.allName}", autoDelete = "true" ), exchange = @Exchange( value = "${mq.config.exchange}", type = ExchangeTypes.TOPIC), key = "*.*.routing.*") ) public class AllReceiver { /** * 设置监听方法 * * @param msg * @RabbitHandler 声明监听方法是下面的 isDefault属性是默认false接受的完整对象,true接受body体 */ @RabbitHandler(isDefault = true) public void process(String msg) { log.info("接受到消息:all {}", msg); } }