RabbitMQ Notes
A message queue (MQ, Message Queue) is essentially a queue that stores messages. It is a cross-process communication mechanism used to pass messages between upstream and downstream systems.
RabbitMQ
The Concept of MQ
MQ (message queue) is essentially a queue with the FIFO (first in, first out) property. The only difference is that it stores “Messages.” It is also a cross-process communication mechanism used to pass messages between upstream and downstream systems. MQ is a common messaging service that provides logical and physical decoupling between upstream and downstream systems.
With MQ, upstream and downstream systems only need to rely on MQ to communicate; no other services are required.
What MQ Can Do
Traffic spike smoothing
By storing tasks as messages in a queue and processing them gradually, this approach protects servers from crashing due to activities such as flash sales. It can also limit the number of tasks in the queue.
Application decoupling
Systems no longer call each other directly. Instead, they use MQ to deliver messages to other systems, thereby achieving decoupling. An exception in one system will not interfere with the normal operation of other systems.
Asynchronous processing
When handling an operation that takes a relatively long time, MQ can pass the task to another thread for asynchronous processing, speeding up response times and improving the user experience.
MQ Categories
ActiveMQ
Developed by Apache. It receives less and less maintenance and is rarely used in high-throughput scenarios.
Kafka
A message queue built for big data, capable of millions of TPS. (It can be chosen for businesses with very large data volumes; Kafka is the first choice for log collection.)
RocketMQ
Developed by Alibaba in Java. It ensures zero message loss and supports the accumulation of billions of messages. Its drawbacks are that it supports few languages, its community is moderately active, and migrating systems requires more code changes. (Built for the financial internet industry, it has been tested during the Double 11 shopping festival.)
RabbitMQ
Currently the most popular message middleware among small and medium-sized companies. It supports many languages and has a highly active community, making it the first choice for small and medium-sized companies.
Four Core Concepts
- Producer: sends messages to an exchange
- Exchange: forwards messages to queues
- Queue: stores messages
- Consumer: consumes messages
Six Patterns
Simple mode: one producer, one queue, one consumer
Work mode: one producer, one queue, multiple consumers
Publish-subscribe mode: one producer, one exchange, multiple queues, multiple consumers
- Fanout (broadcast): sends to all Binding queues;
routingKeyhas no effect
- Fanout (broadcast): sends to all Binding queues;
Routing mode
- Direct (directed): sends to queues with the specified RoutingKey
Topic mode
- Topic (wildcard): sends to queues matching the RoutingPattern
*matches one word#matches zero or more words. Here, words are separated by dots.
Operations
// 声明交换机 Fanout Direct Topic channel.exchangeDeclare(exchangeName, BuiltinExchangeType.TOPIC, false, false, false, null); channel.queueBind(queueName, exchangeName, "routingKey"); //绑定- Topic (wildcard): sends to queues matching the RoutingPattern
RPC
Dead-Letter Queue
Messages in the queue that cannot be correctly processed by consumers
Set up two regular exchanges and queues, and bind a dead-letter exchange and RoutingKey to the regular queue. When a message in this queue becomes a dead letter, it will be forwarded to the dead-letter exchange.
How dead letters are created:
1. The queue is full
1. The message is rejected and not requeued
1. The message expires
Delayed Queue
RabbitMQ does not provide delayed queues, even though delayed queues are commonly used. A simple delayed queue can be implemented by pairing a regular queue with a dead-letter queue: set an expiration time on regular messages and listen to the dead-letter queue.
Problem: However, a delayed queue implemented this way has a fixed timing behavior and cannot support flexible control over delay times. If the first message has a longer expiration time than the second, MQ will only check the first message. If the first message has not expired, it will not check the second message's expiration time, preventing the second message from reaching the queue at the specified time.
Solution: The above approach cannot implement TTL at the message level. Installing a plugin enables RabbitMQ to support delayed queues.
- Download the plugin Official plugin
- Move it to the appropriate directory /usr/lib/rabbitmq/lib/rabbitmq_server-3.8.8/plugins
- Enable the plugin rabbitmq-plugins enable rabbitmq_delayed_message_exchange
- Restart the RabbitMQ service systemctl restart rabbitmq-server It seems you don't need to restart, but restarting is recommended
After installing the plugin, a new x-delayed-message option will be available when creating an exchange.
Delayed Queue Implementation
Create the exchange and queue
@Configuration public class RabbitMQDelayedConfig { public static final String EXCHANGE_NAME = "delayed_exchange"; public static final String QUEUE_NAME = "delayed_queue"; @Bean("delayedExchange") public Exchange DelayedExchange() { return new ExchangeBuilder(EXCHANGE_NAME, ExchangeTypes.FANOUT).delayed().durable(true).build(); } @Bean("delayedQueue") public Queue delayedQueue() { return QueueBuilder.durable(QUEUE_NAME).build(); } @Bean public Binding delayedBinding(@Qualifier("delayedQueue") Queue queue, @Qualifier("delayedExchange") Exchange exchange) { return BindingBuilder.bind(queue).to(exchange).with("").noargs(); } }Send delayed messages
@Test void testDelayedQueue() { rabbitTemplate.convertAndSend(RabbitMQDelayedConfig.EXCHANGE_NAME, "", "delayed Message test", msg -> { msg.getMessageProperties().setDelay(10 * 1000); //延迟时间 ms return msg; } ); }Normal Consumer Operation
Functional Modules
Broker RabbitMQ
Virtual Host Virtual group containing exchanges and queues; belongs to the Broker
Exchange Exchange
Queue Queue
Connection Connection
Channel Channel
Producer Producer
Consumer Consumer
Binding Binding between an exchange and a queue
Install RabbitMQ
Linux:
Required dependencies
Download Erlang from GitHub https://github.com/rabbitmq/erlang-rpm
Download RabbitMQ from GitHub https://github.com/rabbitmq/rabbitmq-server
yum install socat -y rpm -ivh erlang... rpm -ivh rabbitmq...Add to startup items
chkconfig rabbitmq-server on systemctl status rabbitmq-serverConfigure the hostname to resolve to the local IP address
vim /etc/hostsEnable the web-based management page
rabbitmq-plugins enable rabbitmq_management #启用完成后,重启rabbitmq服务 RabbitMQ 的默认访问端口是 15672Set user roles. There are four fixed role levels:
administrator: Can log in to the console, view all information, and manage RabbitMQ
monToring: Monitor; can log in to the console and view all information
policymaker: Policy maker; can log in to the console and define policies
managment: Regular administrator; can log in to the console
rabbitmqctl set_user_tags username role
After installation, a guest user is created by default. However, due to permission restrictions, external users are not allowed to access it, so you need to add a new user for remote management.
````shell
rabbitmq-plugins enable rabbitmq_management
# 创建账号和密码
rabbitmqctl add_user 用户名 密码
# 为用户添加资源权限,添加配置、写、读权限
# set_permissions [-p <vhostpath>] <user> <conf> <write> <read>
rabbitmqctl set_permissions -p "/" y ".*" ".*" ".*"
# 修改密码
rabbitmqctl change_ password 用户名 新密码
# 删除用户
rabbitmqctl delete_user 用户名
# 查看用户清单
rabbitmqctl list_user
````
Using Native RabbitMQ
Basic model: Producer -- Queue -- Consumer
Send messages through a channel, not directly through the connection object.
Utility class code
public class RabbitMQUtil {
/**
* 创建连接工厂 设置rabbitMq服务器的信息
* 获取链接 获取信道
*/
public static Channel getChannel() throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.6.100");
factory.setPort(5672);
factory.setUsername("admin");
factory.setPassword("admin");
Connection connection = factory.newConnection();
return connection.createChannel();
}
}
Producer Code
public class Producer {
public static final String QUEUE_NAME = "hello";
public static void main(String[] args) throws IOException, TimeoutException {
Channel channel = RabbitMQUtil.getChannel();
// 声明一个消息队列 队列名 是否持久化 是否共享队列 是否自动删除 其他参数
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
String message = "Hello world!";
//发送一个消息 指定交换机 路由的KEY值 其他参数 消息
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
}
}
Consumer Code
public class Consumer {
public static final String QUEUE_NAME = "hello";
public static void main(String[] args) throws IOException, TimeoutException {
Channel channel = RabbitMQUtil.getChannel();
DeliverCallback deliverCallback = (consumerTag, message) -> {
System.out.println(new String(message.getBody()));
System.out.println("消费成功的回调执行了。");
};
CancelCallback cancelCallback = (value) -> {
System.out.println("消费中断的回调执行了。");
};
// 消费哪个队列 是否自动应答 消费成功回调 消费者取消消费的回调
channel.basicConsume(QUEUE_NAME, true, deliverCallback, cancelCallback);
}
}
Message Acknowledgment
Message acknowledgment means that after a consumer receives and processes a message, it tells the MQ that processing is complete. The MQ then deletes the message. If the message is not successfully consumed, it will be placed back in the queue after some time. If it cannot be consumed successfully after multiple attempts, it will be sent to the dead-letter queue. During development, try to avoid dead letters and handle messages in the dead-letter queue correctly.
In the consumer code above, automatic message acknowledgment is enabled, so messages are acknowledged automatically after being received. If automatic acknowledgment is disabled, you need to acknowledge messages manually in the callback method, using the passed-in
consumerTag.
Acknowledgment Code
//确认应答 标签 是否批量应答
basicAck(long consumerTag, boolean multiple);
//否定应答 标签
basicNack(long deliveryTag, boolean multiple, boolean requeue);
//否定应答 标签 是否重新入队 (false 直接丢弃消息)
basicReject(long consumerTag, boolean requeue);
//是否恢复消息入队
basicRecover(boolean requeue);
Explanation of Multiple:
The advantage of manual acknowledgments is that they allow messages to be acknowledged in batches and reduce network congestion.
truemeans batch-acknowledging unacknowledged messages on the channel.For example, suppose the channel has messages with delivery tags 5, 6, 7, and 8, and the current tag is 8. In this case, all unacknowledged messages with tags 5–8 will be acknowledged.
Compared with the above,
falseacknowledges only the message withtag=8. Messages 5, 6, and 7 will remain unacknowledged.
Batch acknowledgments must be used carefully to avoid acknowledging messages incorrectly. Their purpose is to prevent requests to the RabbitMQ server from being made too frequently, which would put pressure on the server.
Message Dispatch
Round-robin dispatch
The same number of messages is assigned regardless of each consumer’s ability to process them.
Fair dispatch
Different numbers of messages can be assigned according to each consumer’s ability to process them.
channel.basicQos(int prefetchCount) //开启不公平分发 prefetchCount是预读取数量,当读取了n条时不再接收消息 自然谁执行的快谁就拿到的消息多 如果预取值是0那就是无限的预取值将不断收到消息不管处理消息的能力如何
Message Publisher Confirms
Message confirmation modes:
Prevents messages from failing to publish without the publisher knowing.
Single confirmation
Waits synchronously for message confirmation. This is the safest option, but has the lowest performance. It is relatively slow.
Batch confirmation
Offers better performance than single confirmation, while requiring the fewest connections and placing the least load on the Rabbit server.
Asynchronous batch confirmation
Offers the best performance, but requires writing a listener for asynchronous processing. It is slightly more complicated, but is the optimal solution.
Code example:
channel.confirmSelect(); //开启消息发布确认模式
//单个确认或者批量确认时使用
channel.waitForConfirms(); //将信道中发送的消息进行确认
//使用异步确认模式时使用
//成功时回调
ConfirmCallback ackCallback = (deliveryTag,multiple) ->{
System.out.println("确认的消息:"+deliveryTag);
};
//失败时回调
ConfirmCallback nackCallback= (deliveryTag,multiple) ->{
System.out.println("未确认的消息:"+deliveryTag);
};
// 在信道上进行监听消息并进回调
channel.addConfirmListener(ackCallback,nackCallback);
SpringBoot Integration
Dependencies
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>yml
spring: rabbitmq: host: 192.168.6.100 port: 5672 username: admin password: admin publisher-confirm-type: correlated #开启发布确认模式 publisher-returns: true # 开启returnCallbackConfigure RabbitMQ exchanges, queues, and bindings
@Configuration public class RabbitMQConfig { public static final String EXCHANGE_NAME = "boot_topic_exchange"; public static final String QUEUE_NAME = "boot_topic_queue"; // 声明交换机 @Bean("bootExchange") public Exchange bootExchange() { return ExchangeBuilder.topicExchange(EXCHANGE_NAME).build(); } // 声明队列 @Bean("bootQueue") public Queue bootQueue() { return QueueBuilder.durable(QUEUE_NAME).build(); } // 声明绑定关系 队列 - 交换机 - routingKey @Bean public Binding bindQueueExchange (@Qualifier("bootExchange") Exchange exchange, @Qualifier("bootQueue") Queue queue) { return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs(); } }Producer
// 交换机转发失败return回调 rabbitTemplate.setMandatory(true); //设置交换机将失败的消息发送到returnCallback rabbitTemplate.setReturnsCallback(returnedMessage -> { byte[] body = returnedMessage.getMessage().getBody(); String message = new String(body); System.out.println("失败返回的消息:" + message); }); //消息发送确认回调 rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() { /** * @param correlationData 相关配置信息 * @param ack 是否成功收到消息 * @param cause 失败的原因 */ @Override public void confirm(CorrelationData correlationData, boolean ack, String cause) { if (ack) { System.out.println("消息接收成功"); } else { System.out.println("消息未能成功接收 原因:" + cause); }}}); // 发送消息 rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,"boot.log","hello");Consumers
@Component public class RabbitMQListener { @RabbitListener(queues = "boot_direct_queue1", ackMode = "MANUAL") // 设置独立的确认模式 不设置则遵循全局配置 public void listenBootMessage(Message message, Channel channel) throws IOException { try { System.out.println(new String(message.getBody())); // 处理成功签收消息 channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); //确认签收 } catch (Exception e) { // 出现异常 重回队列 拒签 并且不重回队列,如果绑定了死信队列这条消息将会到达死信队列 channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false); } } }
Other Concepts
Message Idempotency
The results of one or more requests made by a user for the same operation are consistent, and repeated clicks do not cause side effects. The simplest example is a payment: after purchasing a product, the user makes a payment. The payment is successfully deducted, but a network error occurs while the result is being returned. Since the money has already been deducted, the user clicks the button again, triggering a second deduction. This time the result is returned successfully, and the user discovers that they have been charged twice when checking their balance. The transaction history also contains two entries. In a single-application system, we could previously just put data operations in a transaction and roll them back immediately if an error occurred. However, network interruptions or other errors can still occur when responding to the client.
Duplicate Message Consumption/Production
When a consumer consumes a message from MQ, MQ sends the message to the consumer, but the network is interrupted when the consumer returns an ack to MQ. As a result, MQ does not receive the confirmation, and the message is sent again to another consumer, or resent to the same consumer after the network reconnects. In reality, however, the consumer has already successfully consumed the message, resulting in duplicate consumption.
Use a unique message ID to prevent duplicate consumption and production. This can be implemented in conjunction with Redis
SETNX.
Queue Priority
Use case: When order volumes are high in a shopping system, increase the processing priority of orders from stores that generate greater value.
Configure the queue'sx-max-priorityparameter. The maximum is 255, but the official recommendation is 1–10; otherwise, it will consume excessive system resources.
Priority must also be configured when sending messages.
Once priority is configured, messages in the queue will be reordered, and higher-priority messages will be consumed first.
Lazy Queues
If a consumer is offline for maintenance or goes down, a large number of messages can accumulate in memory, causing memory usage to continually increase. In this situation, lazy queues are needed to store messages on disk and avoid excessive memory consumption.