@Configuration public class RabbitMqConfig { public static final String EXCHANGE_DIRECT_NAME="direct_exchange"; public static final String EXCHANGE_TOPIC_NAME="topic_exchange"; public static final String EXCHANGE_FANOUT_NAME="fanout_exchange"; public static final String QUEUE_NAME="queque"; /** *direct类型会把消息路由到那些binding key与routing key完全匹配的Queue中。 * (在实际使用RabbitMQ的过程中并没有binding key这个参数,只有routing key,为了区分我们把交换机和队列绑定时传的参数叫binding key,把发送消息时带的这个参数叫routing key) * durable :是否持久化 * autoDelete:是否自动删除,当没有consumer时,自动删除掉 * exclusive :1.是否独占,只能有一个消费者监听这个队列 * 2.当connection关闭时,是否删除队列 */ @Bean("dirctExchange") public Exchange dirctExchange(){ return ExchangeBuilder.directExchange(EXCHANGE_DIRECT_NAME).durable(true).build(); } /** *(通配符交换机) 对key进行模式匹配后进行投递,符号”#”匹配一个或多个词,符号”*”匹配正好一个词。例如”abc.#”匹配”abc.def.ghi”,”abc.*”只匹配”abc.def” * @return */ @Bean("topicExchange") public Exchange topicExchange(){ return ExchangeBuilder.topicExchange(EXCHANGE_TOPIC_NAME).durable(true).build(); } /** * (扇型交换机) 不需要key,它采取广播模式,一个消息进来时,投递到与该交换机绑定的所有队列 * @return */ @Bean("fanoutExchange") public Exchange fanoutExchange(){ return ExchangeBuilder.fanoutExchange(EXCHANGE_FANOUT_NAME).durable(true).build(); } // 消息队列 @Bean("queue") public Queue queue(){ return QueueBuilder.durable(QUEUE_NAME).build(); } // 绑定交换机和消息队列 @Bean public Binding bindQueueExchange(@Qualifier("dirctExchange") Exchange exchange, Queue queue){ return BindingBuilder.bind(queue).to(exchange).with("abc.top").noargs(); } }
消费者
@Component public class ConsumerListener { @RabbitListener(queues = "queque") public void getMessage(Message message){ // 接收信息 System.out.println(new String(message.getBody())); } }
application.properties
spring.rabbitmq.host=locahost spring.rabbitmq.port=5672 spring.rabbitmq.username=guest spring.rabbitmq.password=guest