When using RabbitMQ, sometimes when we send a message to producers RabbitMQ server, our producer wanted to know whether the message reached the RabbitMQ server. How should we deal with this time ?
In response to these problems, RabbitMQ provides 2 solutions.
- Achieved through a transaction mechanism ( not recommended )
- Implementation Mechanism by sending a confirmation (publisher confirm) ( recommended )
- note:
- 1, the embodiment 2 above can not coexist only select one of the transaction if the opening is turned on and confirm a channel error occurs.
- 2, if the transmission of the message does not match the switch's queue, then the message is lost.
Achieved through transaction mechanism
RabbitMQ client-related transaction mechanism There are three methods.
channel.txSelect (): the current channel to the transaction mode for setting
channel.txCommit (): used to commit the transaction ( transaction commit succeeds, the message must reach the RabbitMQ server )
channel.txRollback (): used to roll back the transaction
Code java producers transaction implementation are as follows:
Note: The transaction mechanism to make after sending a message to the sender blocked after RabbitMQ server response in order to continue to send a message, the possible performance is not very good in the case of high concurrency, therefore not recommended.
Sender acknowledgment mechanism (Comfirm Listener)
Confirmation message-there are several, the highest efficiency asynchronous acknowledgment mechanism described here.
Asynchronous acknowledgment mechanism:
1, using channel.confirmSelect () to confirm the channel setting mode
2, channel.addConfirmListener monitor whether the message arrives RabbitmqMQ
Listeners deliverTag and multiple parameters see Figure below explained.
After producer will set to confirm channel mode, published message on this channel will be assigned a unique ID (starting at 1), when the message is not routed to the exchange after the matched queue, if the message is persistent, then after the message persistent, RabbitMQ sends an acknowledgment (Basic.Ack) to the producer (the unique ID contained in the message), so that the producer knows the RabbitMQ message arrived correctly.
Manufacturer Code java asynchronous acknowledgment to achieve the following:
Complete code:
Transaction confirmation: https://gitee.com/huan1993/rabbitmq/tree/master/rabbitmq-advance/src/main/java/com/huan/rabbitmq/advance/produceconfirm/tx