SpringBoot 整合 RabbitMQ 五种消息模型实战
RabbitMQ 是消息队列中的主流方案。这篇讲 SpringBoot 整合 RabbitMQ 的五种消息模型。
一、引入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId></dependency>二、配置
spring:rabbitmq:host:localhostport:5672username:guestpassword:guest三、工作队列模式(Work Queue)
@ConfigurationpublicclassRabbitConfig{publicstaticfinalStringQUEUE="queue.work";@BeanpublicQueueworkQueue(){returnnewQueue(QUEUE);}}@ServicepublicclassWorkProducer{@AutowiredprivateRabbitTemplaterabbitTemplate;publicvoidsend(Stringmessage){for(inti=0;i<10;i++){rabbitTemplate.convertAndSend(RabbitConfig.QUEUE,message+":"+i);}}}@ComponentpublicclassWorkConsumer1{@RabbitListener(queues=RabbitConfig.QUEUE)publicvoidreceive(Stringmessage){System.out.println("消费者1收到: "+message);try{Thread.sleep(1000);}catch(Exceptione){}}}四、发布订阅模式(Publish/Subscribe)
@ConfigurationpublicclassFanoutConfig{@BeanpublicFanoutExchangefanoutExchange(){returnnewFanoutExchange("exchange.fanout");}@BeanpublicQueuequeueA(){returnnewQueue("queue.fanout.a");}@BeanpublicQueuequeueB(){returnnewQueue("queue.fanout.b");}@BeanpublicBindingbindingA(){returnBindingBuilder.bind(queueA()).to(fanoutExchange());}@BeanpublicBindingbindingB(){returnBindingBuilder.bind(queueB()).to(fanoutExchange());}}五、路由模式(Routing)
@ConfigurationpublicclassDirectConfig{publicstaticfinalStringQUEUE_INFO="queue.direct.info";publicstaticfinalStringQUEUE_ERROR="queue.direct.error";@BeanpublicDirectExchangedirectExchange(){returnnewDirectExchange("exchange.direct");}@BeanpublicQueueinfoQueue(){returnnewQueue(QUEUE_INFO);}@BeanpublicQueueerrorQueue(){returnnewQueue(QUEUE_ERROR);}@BeanpublicBindinginfoBinding(){returnBindingBuilder.bind(infoQueue()).to(directExchange()).with("info");}@BeanpublicBindingerrorBinding(){returnBindingBuilder.bind(errorQueue()).to(directExchange()).with("error");}}@ServicepublicclassDirectProducer{@AutowiredprivateRabbitTemplaterabbitTemplate;publicvoidsendError(Stringmessage){// 只有 errorQueue 会收到rabbitTemplate.convertAndSend("exchange.direct","error",message);}}六、主题模式(Topic)
@ConfigurationpublicclassTopicConfig{@BeanpublicTopicExchangetopicExchange(){returnnewTopicExchange("exchange.topic");}@BeanpublicQueueorderQueue(){returnnewQueue("queue.topic.order");}@BeanpublicQueueuserQueue(){returnnewQueue("queue.topic.user");}@BeanpublicBindingorderBinding(){returnBindingBuilder.bind(orderQueue()).to(topicExchange()).with("order.*");}@BeanpublicBindinguserBinding(){returnBindingBuilder.bind(userQueue()).to(topicExchange()).with("user.#");}}七、五种模型对比
| 模型 | Exchange类型 | 路由方式 | 场景 |
|---|---|---|---|
| 简单/工作 | 无(默认) | 直接 | 任务分发 |
| 发布订阅 | Fanout | 广播 | 通知所有消费者 |
| 路由 | Direct | 精确匹配 | 按级别分发 |
| 主题 | Topic | 通配符 | 复杂路由 |
| RPC | 无 | 同步 | 请求-响应 |
💡 觉得有用的话,点赞 + 关注【张老师技术栈】吧!
