When there are a large number of messages in the queue, it puts a heavy burden on memory usage. In order to free up memory, RabbitMQ flushes the messages to disk. This process usually takes time, and restarting a cluster with a large number of messages is time-consuming due to the need to rebuild the index. When too many messages are flushed, the queue will be blocked from processing messages, thereby reducing the queue speed and negatively affecting the performance of the RabbitMQ node.
For best performance, the queue should be kept as short as possible. It is recommended to always keep the number of queue message accumulation around 0.
For applications that are frequently affected by message spikes, and those require high throughput, it is recommended to set a maximum length on the queue. This can maintain the queue length by discarding the messages in the queue header, and the queue length will never exceed the maximum length setting.
Use the corresponding parameter settings when declaring the queue.
//Create queue
HashMap<String, Object> map = new HashMap<>();
//Set the length of the quorum queue
map.put("x-max-length",10 );
//Set the queue overflow mode to keep the top 10
map.put("x-overflow","reject-publish" );
channel.queueDeclare(queueName,false,false,false,map);
When the queue length exceeds the set maximum length, RabbitMQ's default practice is to discard the information at the head of the queue (the oldest message in the queue) or turn it into dead letter. This method can be changed by setting different overflow values. If the overflow value is set to drop-head, it means dropping or dead-letter messages from the front of the queue and saving the last n messages. If the overflow value is set to reject-publish, the most recently published messages will be discarded, that is, the first n messages will be saved.