I am writing a Java application using ActiveMQ. I have a Producer Class (which takes user input) and a Consumer Class with a listener, so that as soon as messages arrive, Message Listener executes the onMessage(msg) function. My question, though, is when does a consumer sends back the acknowledgement to the broker, so that the msg is de-queued from the broker? Is it after completing the actions written in the onMessage(msg) function or is it just when the onMessage(msg) function is invoked?
问题:
回答1:
In the normal case the ack is sent after the onMessage completes since it needs to handle the case of onMessage throwing an exception.
回答2:
Depends how it's configured, and in part on how you use transactions.
Are you using a message-driven bean? In that case, i believe the acknowledgement will be sent when the transaction is successfully committed. See the specification (specifically the 'ejbcore' version), section 5.4.14 Message Acknowledgment for JMS Message-Driven Beans, which says:
Message acknowledgment is automatically handled by the container. If the message-driven bean uses container-managed transaction demarcation, message acknowledgment is handled automatically as a part ofthe transaction commit.
It goes on to say:
If bean-managed transaction demarcation is used, the message receipt cannot be part of the bean-managed transaction, and, in this case, the receipt is acknowledged by the container. If bean-managed transaction demarcation is used, the Bean Provider can indicate whether JMS
AUTO_ACKNOWLEDGE
semantics orDUPS_OK_ACKNOWLEDGE
semantics should apply by using theactivationConfig
element of theMessageDriven
annotation or by using theactivation-config-property
deployment descriptor element.
But since you really shouldn't be using bean-managed transactions, that is hopefully irrelevant.