package com.example.springboot.common;
|
|
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 RabbitConfig {
|
|
// 定义交换机名称
|
public static final String DIRECT_EXCHANGE_NAME = "direct.exchange";
|
// 定义队列名称
|
public static final String QUEUE_NAME = "canadames";
|
// 定义路由键
|
public static final String ROUTING_KEY = "message.routingKey";
|
// 定义第二个队列名称
|
public static final String SECOND_QUEUE_NAME = "anotherQueue";
|
// 定义第二个路由键
|
public static final String SECOND_ROUTING_KEY = "another.routingKey";
|
|
// 定义交换机
|
|
// 直连交换机(Direct Exchange):直连交换机是最简单的一种交换机类型。它根据消息的路由键(Routing Key)将消息发送到与之完全匹配的队列。
|
// 主题交换机(Topic Exchange):主题交换机允许通过使用通配符的方式来进行消息的路由。它将消息根据匹配的规则(通配符)发送到一个或多个队列上
|
//扇形交换机(Fanout Exchange):扇形交换机会将收到的所有消息广播到所有绑定的队列上。它忽略消息的路由键,只需将消息发送给所有绑定的队列。
|
@Bean
|
public DirectExchange directExchange() {
|
return new DirectExchange(DIRECT_EXCHANGE_NAME);
|
}
|
|
// 定义队列
|
@Bean
|
public Queue queue() {
|
return new Queue(QUEUE_NAME);
|
}
|
|
// 定义第二个队列
|
@Bean
|
public Queue secondQueue() {
|
return new Queue(SECOND_QUEUE_NAME);
|
}
|
|
//第二个参数表示队列是否为持久化的,如果你想要创建一个持久化的队列,可以将该参数设置为 true。
|
// 持久化队列可以在 RabbitMQ 服务器重启后继续存在,以防止消息丢失。
|
//第三个参数 exclusive 设置为 false,表示队列非排他性;
|
// 将第四个参数 autoDelete 设置为 false,表示队列不会自动删除;
|
// 将第五个参数 arguments 设置为 null,表示不指定其他参数。
|
// @Bean
|
// public Queue queue() {
|
// return new Queue(QUEUE_NAME, false, false, false, null);
|
// }
|
|
// 将队列绑定到交换机上,并指定路由键
|
@Bean
|
public Binding binding() {
|
return BindingBuilder.bind(queue()).to(directExchange()).with(ROUTING_KEY);
|
}
|
|
// 将第二个队列绑定到交换机上,并指定第二个路由键
|
@Bean
|
public Binding secondBinding() {
|
return BindingBuilder.bind(secondQueue()).to(directExchange()).with(SECOND_ROUTING_KEY);
|
}
|
}
|