赞
踩
RabbitMQ 是一个消息队列中间件,主要用于异步处理、解耦和缓冲。它实现了高级的消息队列协议(AMQP),并提供了可靠性、强大的管理界面和丰富的客户端库,是非常流行的分布式消息系统。
RabbitMQ 的基本思想是生产者将消息发送到队列中,然后消费者从队列中取出消息进行处理。在 RabbitMQ 中,生产者和消费者不知道对方的存在,并且服务于 RabbitMQ Broker 上,即使有一端暂停了也不会影响另外一端的工作,从而保证了整个系统的稳定性和可靠性。
RabbitMQ 通过 AMQP(Advanced Message Queuing Protocol)实现了传输超时、负载均衡、分发路由等一系列功能,具有以下几个优点:
可靠性:RabbitMQ 通过持久化和数据备份来保证消息可靠性。
可拓展性:可以通过添加新服务器来扩展应用程序的容量,从而增加资源利用率。
高可用性:多节点环境下,在某个节点失效的情况下,其它节点负责接替工作,从而保证 RabbitMQ 服务的高可用性。
灵活性:RabbitMQ 具有灵活的交换机和堆栈路由器等机制,能够实现多种消息传递模型。
可维护性:RabbitMQ 提供了Web管理控制台,可以方便地查看队列状态、消息大小等信息,并进行开发工具集成。
总之,RabbitMQ 具有高性能、高可用性、简单易用、灵活可扩展等优点,被广泛应用于分布式系统和云计算架构中。
- <!-- Maven -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-amqp</artifactId>
- </dependency>
- spring:
- rabbitmq:
- host: localhost
- port: 5123
- username: qql
- password: qql
- import org.springframework.amqp.core.*;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
-
- @Configuration
- public class RabbitMQConfig {
-
- @Bean
- public Queue myQueue() {
- return new Queue("qqlQueue");
- }
-
- @Bean
- public DirectExchange myExchange() {
- return new DirectExchange("qqlExchange");
- }
-
- @Bean
- public Binding binding(Queue myQueue, DirectExchange myExchange) {
- return BindingBuilder.bind(myQueue).to(myExchange).with("qqlRoutingKey");
- }
- }

- import org.springframework.amqp.rabbit.core.RabbitTemplate;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Component;
-
- @Component
- public class RabbitMQProducer {
-
- @Autowired
- private RabbitTemplate rabbitTemplate;
-
- public void send(String exchange, String routingKey, String message) {
- rabbitTemplate.convertAndSend(exchange, routingKey, message);
- }
- }
- import org.springframework.amqp.rabbit.annotation.RabbitListener;
- import org.springframework.stereotype.Component;
-
- @Component
- public class RabbitMQConsumer {
-
- @RabbitListener(queues = "qqlQueue")
- public void handleMessage(String message) {
- System.out.println("message: " + message);
- }
- }
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.bind.annotation.RestController;
-
- @RestController
- public class MessageController {
-
- @Autowired
- private RabbitMQProducer rabbitMQProducer;
-
- @PostMapping("/send")
- public String sendMessage(@RequestParam("message") String message) {
- rabbitMQProducer.send("qqlExchange", "qqlRoutingKey", message);
- return "Success!";
- }
- }

启动项目后,访问 http://localhost:端口号/send?message=Hello+World
,您将看到控制台输出接收到的消息:“message: Hello World”。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。