How to realize the sequential consumption of messages in MQ

Among the common MQ middleware, RocketMQ implements sequential consumption support. Other MQs basically do not support sequential consumption at the MQ level. After all, ensuring the order will have a great impact on performance.

The order of consumption

When the message is not in the same queue or when there are multiple consumers in the same queue, there will be a problem with the order of consumption. If there is only one queue, only one consumer and each time a message is obtained for consumption, then the message must It is consumed in order.

Global sequential consumption

  • All messages entering MQ must be consumed in order. If this order is to be achieved, the performance of MQ will be greatly reduced.

Partial sequential consumption

  • Partial sequential consumption means that messages in certain scenarios need to be consumed in order, for example, order creation, payment, and delivery are an orderly process, and payment cannot be made before order creation

The realization of sequential consumption

1. Single Queue + Single Consumer Mode

  • If the business is simple and the accumulation of MQ messages is small, you can use a Queue and a consumer to ensure the sequential consumption of messages, so that as long as the messages are produced in order and put into the same Queue, they can be the same in the order of input One consumer

2. Message body sequence identification + warehouse drop + consumer logic judgment

  • Add the sequence identifier and group identifier to the message body that needs to be consumed in sequence, and store it in the data table after sending. Before the consumer receives the message and consumes it, query the data table to determine whether the message that belongs to the first order in the same group has been consumed, if not, then Reject the ack to be delivered again.

Take the ordering scene as an example

Place an order and cancel an order respectively correspond to a message with an order number of 1234 and a sequence of 10 and a message with an order number of 1234 and a sequence of 20. After the producer sends the two messages, the two messages are stored in the database. If the message of canceling the order is first sent by the consumer Receive first, before executing the consumption logic, first query the data table for messages with an order number of 1234 and less than 20, and whether they have been consumed. If they have not been consumed, reject ack until the order message is consumed. Only then can the consumption of the cancel order message be executed

Guess you like

Origin blog.csdn.net/qq_29569183/article/details/115036108