RabbitMQ springboot Routing路由(Direct)订阅模式-消费者工程2 作者:马育民 • 2021-08-22 20:46 • 阅读:10037 上接:[RabbitMQ springboot创建父工程](https://www.malaoshi.top/show_1IX1ib4sCCGu.html "RabbitMQ springboot创建父工程") # 创建消费者子模块 在父项目中,创建消费者子模块:direct_order 略 # pom.xml 由于父项目已引入所有依赖包,所以pom.xml中不做任何修改 # application.yml ``` server: port: 8002 spring: application: #服务名称 name: rabbitmq-direct-order #RabbitMQ的配置 rabbitmq: host: 127.0.0.1 port: 5672 username: guest password: guest ``` # 创建 RabbitMQ 监听器 生产者需要事先创建队列,然后才能发送消息,所以增加 **配置类**,启动时,自动创建 queue,这里是:notice ``` package top.malaoshi.rabbitmq; import com.rabbitmq.client.Channel; import org.springframework.amqp.core.ExchangeTypes; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.annotation.Exchange; import org.springframework.amqp.rabbit.annotation.Queue; import org.springframework.amqp.rabbit.annotation.QueueBinding; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component public class ConsumerListener { public static final String QUEUE_ORDER="direct_order"; public static final String EXCHANGE="direct_exchange"; public static final String KEY_ORDER="key_order"; //注册监听器,并指定消息队列名称 @RabbitListener( bindings = @QueueBinding( value = @Queue(QUEUE_ORDER), key = KEY_ORDER, exchange = @Exchange( value = EXCHANGE, type = ExchangeTypes.DIRECT))) public void receiveMsg(String msg, Channel channel, Message message){ //msg:字符串消息 System.out.println("收到消息:" + msg); System.out.println("channel通道编号为:" + channel.getChannelNumber()); //可以通过Message对象,获取消息正文 System.out.println("收到消息:" + new String(message.getBody())); } } ``` ### @RabbitListener 自动创建队列、交换器,并进行绑定 ``` @RabbitListener( bindings = @QueueBinding( value = @Queue(QUEUE_ORDER), key = KEY_ORDER, exchange = @Exchange( value = EXCHANGE, type = ExchangeTypes.DIRECT))) ``` - 指定队列名称 - 指定交换器名称 - 指定 `key = KEY_ORDER`,即:**RoutingKey** - 可以不指定 交换器类型:`type = ExchangeTypes.DIRECT`,因为默认为 `direct` # 主启动类 ``` package org.malaoshi; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class NoticeMain { public static void main(String[] args) { SpringApplication.run(NoticeMain.class, args); } } ``` # 启动服务 启动主启动类 控制台会打印接收到的消息: ``` 收到消息:iphone channel通道编号为:1 收到消息:iphone ``` # 访问 rabbitmq web管理页面 此时创建 消息队列 `direct_order` 了 原文出处:http://malaoshi.top/show_1IX1ix6yZIJb.html