ActiveMQ - is it possible to acknowledge single me

2020-07-25 23:44发布

问题:

According to http://docs.oracle.com/javaee/6/api/javax/jms/Message.html#acknowledge()

A client may individually acknowledge each message as it is consumed, or it may choose to acknowledge messages as an application-defined group (which is done by calling acknowledge on the last received message of the group, thereby acknowledging all messages consumed by the session.)

How can I do it in ActiveMQ? I was unable to make it work.

回答1:

here is example with ActiveMQ client,

import javax.jms.Connection;
import javax.jms.JMSException;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQMessageConsumer;
import org.apache.activemq.ActiveMQSession;
import org.apache.activemq.command.ActiveMQTextMessage;

public class SimpleConsumer {

    public static void main(String[] args) throws JMSException {
        Connection conn = null;
        try {
            ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616");
            conn = cf.createConnection("consumer", "consumer");
            ActiveMQSession session = (ActiveMQSession) conn.createSession(false,
                    ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE);
            ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer) session
                    .createConsumer(session.createQueue("QUEUE"));
            conn.start();
            ActiveMQTextMessage msg = null;
            while ((msg = (ActiveMQTextMessage) consumer.receive()) != null) {
                System.out.println("Received message is: " + msg.getText());
                msg.acknowledge();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                }
            }
        }
    }
}


回答2:

I am correcting my answer after the below comments with Matt Pavlovich.

CLIENT_ACKNOWLEDGE: With this option, a client acknowledges a message by calling the message’s acknowledge method. Acknowledging a consumed message automatically acknowledges the receipt of all messages that have been delivered by its session.

So, the CLIENT_ACKNOWLEDGE option can NOT be used to send an acknowledgment to the JMS provider for a single message.

You can look at spec here:

http://download.oracle.com/otndocs/jcp/jms-2_0-fr-eval-spec/index.html



标签: jms activemq