6、路由模式(direct)
1)、配置类
package com.shenmazong.demorabbitmq0706.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DirectMqConfig {
//定义声明所有的组件,交换机,队列queue,将
//之间的关系绑定,完成一个路由模式
@Bean
public Queue queueRed(){
return new Queue("queueRed", false, false, false);
}
@Bean
public Queue queueGreen(){
return new Queue("queueGreen", false, false, false);
}
//声明交换机,不同类型的交换机对应不同类
@Bean
public DirectExchange ex(){
return new DirectExchange("directEx");
}
//路由绑定关系
@Bean
public Binding bindRed(){
return BindingBuilder.bind(queueRed()).to(ex())
.with("msg.red");
}
@Bean
public Binding bindGreen() {
return BindingBuilder.bind(queueGreen()).to(ex()).with("msg.green");
}
}
2)、消费者
package com.shenmazong.demorabbitmq0706.listenner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class DirectReceiver {
@RabbitListener(queues = "queueRed")
public void onRedMessage(String message) {
log.info("queueRed:"+message);
}
@RabbitListener(queues = "queueGreen")
public void onGreenMessage(String message) {
log.info("queueGreen:"+message);
}
}
3)、生产者
@GetMapping(value = "/directMessage")
public Object directMessage() {
for(int ndx=0; ndx<10; ndx++) {
if((ndx%2) == 0) {
amqpTemplate.convertAndSend("directEx", "msg.red", idx++ + ",red message");
}
else {
amqpTemplate.convertAndSend("directEx", "msg.green", idx++ + ",green message");
}
}
return idx;
}
4)、运行截图
7、主题模式(topic)