开始创建
引入依赖
<!--AMQP依赖,包含RabbitMQ-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
<version>2.7.12</version>
</dependency>
创建Fanout类型的交换机(编码创建)
广播,将消息交给所有绑定到交换机的队列
@Configuration
public class FanoutConfiguration {
/*声明交换机*/
@Bean
public FanoutExchange fanoutExchange() {
//交换机名称
return ExchangeBuilder.fanoutExchange("amq.fanout").build();
}
/*声明队列*/
@Bean
public Queue queue1() {
//队列名称
return QueueBuilder.durable("fanout.queue1").build();
}
@Bean
public Queue queue2() {
return QueueBuilder.durable("fanout.queue2").build();
}
/*绑定队列与交换机*/
@Bean
public Binding fanoutQueue1Binding(Queue queue1, FanoutExchange fanoutExchange) {
return BindingBuilder.bind(queue1).to(fanoutExchange);
}
/*绑定队列与交换机*/
@Bean
public Binding fanoutQueue2Binding(Queue queue2, FanoutExchange fanoutExchange) {
return BindingBuilder.bind(queue2).to(fanoutExchange);
}
}
创建Direct类型的交换机(编码创建)
订阅制广播方式
@Configuration
public class DirectConfig {
/**
* 声明交换机
* @return Direct类型交换机
*/
@Bean
public DirectExchange directExchange(){
return ExchangeBuilder.directExchange("amq.direct").build();
}
/**
* 第1个队列
*/
@Bean
public Queue directQueue1(){
return new Queue("direct.queue1");
}
/**
* 绑定队列和交换机
*/
@Bean
public Binding bindingQueue1WithRed(Queue directQueue1, DirectExchange directExchange){
return BindingBuilder.bind(directQueue1).to(directExchange).with("red");
}
/**
* 绑定队列和交换机
*/
@Bean
public Binding bindingQueue1WithBlue(Queue directQueue1, DirectExchange directExchange){
return BindingBuilder.bind(directQueue1).to(directExchange).with("blue");
}
/**
* 第2个队列
*/
@Bean
public Queue directQueue2(){
return new Queue("direct.queue2");
}
/**
* 绑定队列和交换机
*/
@Bean
public Binding bindingQueue2WithRed(Queue directQueue2, DirectExchange directExchange){
return BindingBuilder.bind(directQueue2).to(directExchange).with("red");
}
/**
* 绑定队列和交换机
*/
@Bean
public Binding bindingQueue2WithYellow(Queue directQueue2, DirectExchange directExchange){
return BindingBuilder.bind(directQueue2).to(directExchange).with("yellow");
}
创建Direct类型的交换机(声明创建)
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "direct.queue2", declare = "true"),
exchange = @Exchange(name = "amq.direct", type = ExchangeTypes.DIRECT, declare = "true"),
key = {"red", "yellow"}
))
@RabbitListener(queues = "direct.queue2")
public void listenerDirectQueueMess2(String mess) {
log.info("direct.queues2:【{}】", mess);
}
启动项目
现在启动项目然后去 mq 的管理页面查看是否创建成功