RabbitMQ之Direct交换器模式开发

Dirtct交换器,即发布与订阅模式,匹配规则为完全匹配。

 

一、Provideer

配置文件

 1 spring.application.name=provider
 2 spring.rabbitmq.host=192.168.50.30
 3 spring.rabbitmq.port=5672
 4 spring.rabbitmq.username=rabbit
 5 spring.rabbitmq.password=rabbit
 6 #设置交换器的名称
 7 mq.config.exchange=log.direct
 8 #info 路由键
 9 mq.config.queue.info.routing.key=log.info.routing.key
10 #error 路由键
11 mq.config.queue.error.routing.key=log.error.routing.key
12 #error 队列名称
13 mq.config.queue.error=log.error

代码

 1 @Component
 2 public class Sender {
 3     @Autowired
 4     private AmqpTemplate amqpTemplate;
 5     
 6     @Value("${mq.config.exchange}")
 7     private String exchange;
 8 
 9     @Value("${mq.config.queue.error.routing.key}")
10     private String routingkey;
11 
12     public void send(String msg) {
13         this.amqpTemplate.convertAndSend(this.exchange, this.routingkey, msg);
14     }
15 }

二、consumer

配置文件

 1 spring.application.name=consumer
 2 spring.rabbitmq.host=192.168.50.30
 3 spring.rabbitmq.port=5672
 4 spring.rabbitmq.username=rabbit
 5 spring.rabbitmq.password=rabbit
 6 #设置交换器名称
 7 mq.config.exchange=log.direct
 8 #info队列名称
 9 mq.config.queue.info=log.info
10 #info路由键
11 mq.config.queue.info.routing.key=log.info.routing.key
12 #error队列名称
13 mq.config.queqe.error=log.error
14 #errot路由键
15 mq.config.queue.error.routing.key=log.error.routing.key

1,InfoReceiver

 1 /*
 2 @RabbitListener bindings:绑定队列
 3 @QueueBinding value:绑定队列的名称
 4             exchange:配置交换器
 5 @Queue value:配置队列名称
 6         autoDelete:是否是一个可删除的临时队列
 7 @Exchange value:为交换器起个名称
 8         type:指定具体交换器类型
 9  */
10 @Component
11 @RabbitListener(
12     bindings=@QueueBinding(
13         value=@Queue(
14             value="${mq.config.queue.info}", 
15             autoDelete="true"
16         ),
17         exchange=@Exchange(
18             value="${mq.config.exchange}",
19             type=ExchangeTypes.DIRECT
20         ),
21         key="${mq.config.queue.info.routing.key}"
22     )
23 )
24 public class Consumer {
25     @RabbitHandler
26     public void process(String msg) {
27         System.out.println("info received:" + msg);
28     }
29 }

2,ErrorReceiver

 1 /*
 2 @RabbitListener bindings:绑定队列
 3 @QueueBinding value:绑定队列的名称
 4             exchange:配置交换器
 5 @Queue value:配置队列名称
 6         autoDelete:是否是一个可删除的临时队列
 7 @Exchange value:为具体交换器起个名称
 8         type:指定具体的交换类型
 9  */
10 @Component
11 @RabbitListener(
12     bindings=@QueueBinding(
13         value=@Queue(
14             value="${mq.config.queue.error}",
15             autoDelete="true"
16         ),
17         exchange=@Exchange(
18             value="${mq.config.exchange}",
19             type=ExchangeTypes.DIRECT
20         ),
21         key="${mq.config.queue.error.routing.key}"
22     )
23 )
24 public class ErrorReceiver {
25     public void process(String msg) {
26         System.out.println("error recevied:" + msg);
27     }
28 }
原文地址:https://www.cnblogs.com/guanghe/p/11026662.html