文章目录[隐藏]
本文主要聊SpringBoot整合RabbitMQ,主要分为生产者和消费者两个工程,目录结构如下:
先简单说一下RabbitMQ的一些核心概念:
1.虚拟主机vhost:vhost是本文来源gao*daima.com搞@代#码&网6物理隔离的,你可以将vhost看作是一个个小型的RabbitMQ
2.交换机exchange:生产者发送的消息不是直接到达队列的,而是交换机,然后交换机再根据路由key,路由到指定的队列,可以理解为一个分发消息的角色
3.队列:存放消息的地方,消费者拿到的消息就是通过队列,可以理解为存放消息的容器
4.bindingKey和routingKey:这两个可能比较容易搞混,bindingKey是交换机和队列建立关系时候的key,而routingKey则是生产者发送消息时候的key。在DirectExchange类型的交换机中,bindingKey和routingKey是一致的,而在TopicExchange类型的交换机中,两者一般是不一致的。
开发环境:RabbitMQ:3.7.7、SpringBoot2.1.7
引入相关依赖:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.1.7.RELEASE</version> </dependency> <!-- rabbitmq依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> <version>2.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <version>2.1.7.RELEASE</version> </dependency> </dependencies>
在生产者和消费者工程的application.yml文件添加RabbitMQ配置:
spring: rabbitmq: host: localhost port: 5672 username: guest password: guest
如果是和上面一样的值,其实也可以不用配置,因为RabbitMQ的默认配置就是它们:
接下来,看看几种交换机的使用场景,包括:
(1)fanout:发布订阅型,可以理解为广播
(2)direct:直连型,可以理解为点对点
(3)topic:通配符模式
一、fanout:发布订阅型
在生产者工程,添加如下配置:
@Configuration public class FanoutRabbitmqConfig { public static final String EMAIL_QUEUE = "email_fanout"; public static final String SMS_QUEUE = "sms_fanout"; public static final String EXCHANGE_NAME = "exchange_fanout"; // 发布订阅模式,不用routingKey @Bean public FanoutExchange getFanoutExchange(){ return new FanoutExchange(EXCHANGE_NAME); } @Bean public Queue getFanoutEmailQueue(){ return new Queue(EMAIL_QUEUE); } @Bean public Queue getFanoutSmsQueue(){ return new Queue(SMS_QUEUE); } // 绑定交换机和队列 @Bean public Binding fanoutEmailExchange(){ return BindingBuilder.bind(getFanoutEmailQueue()).to(getFanoutExchange()); } @Bean public Binding fanoutSmsExchange(){ return BindingBuilder.bind(getFanoutSmsQueue()).to(getFanoutExchange()); } // 用于测试找到了交换机,但是没有找到队列的情况 @Bean public FanoutExchange notBindingQueue(){ return new FanoutExchange("testNotBindingQueue"); } }