How to rollback messages in Activemq

2019-06-03 05:26发布

问题:

I want to send acknowledgement to Activemq when variable x value is equals to 1.If it not equals to 1,I want to redeliver messages to Activemq. Then only Activemq delivers that messages again to subscribers.For this I written the following programs.

MessageConsumer.java :

 public class Consumer extends HttpServlet {
 @Override
 protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
    throws ServletException, IOException {
  try {
    ActiveMQConnectionFactory connectionFactory=new ActiveMQConnectionFactory("admin","admin","tcp://localhost:61617");
RedeliveryPolicy policy = new RedeliveryPolicy();
policy.setInitialRedeliveryDelay(1000L);
policy.setMaximumRedeliveries(RedeliveryPolicy.NO_MAXIMUM_REDELIVERIES);
connectionFactory.setRedeliveryPolicy(policy);
connectionFactory.setUseRetroactiveConsumer(true);
Connection connection=connectionFactory.createConnection();
final Session session=connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
Topic queue=session.createTopic("MessageTesting");
javax.jms.MessageConsumer consumer=session.createConsumer(queue);
//anonymous class
MessageListener listener = new MessageListener() {
        @Override
    public void onMessage(Message msg) {
        TextMessage msg1=(TextMessage)msg;
        try {
                String messageBody=msg1.getText();
                if (x==1) {
                   //Process was completely done,so I am sending acknowledge
                   session.commit();
                }  
                else {
                   //Process is not done sucessfully, So I want to redeliver messages, For this
                   session.rollback();
                 }
           }
          catch (Exception e) {
                 e.printStackTrace();
           }

    }
};
consumer.setMessageListener(listener);
connection.start();
}
 }

Is this correct way to do this.can you suggest me,Is there any efficient way.

Thanks.

回答1:

Ideally, you will have to :

Create a ActiveMQConnectionFactory to your binding address, Create a RedeliveryPolicy and set it to ActiveMQConnectionFactory. Create a Session and use session.commit() if true and session.rollback() if it failed.

These two links might help you:

http://activemq.apache.org/message-redelivery-and-dlq-handling.html

http://activemq.apache.org/redelivery-policy.html

public class Consumer extends HttpServlet {
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException {
try {
...
MessageListener listener = new MessageListener() {
public void onMessage(Message msg) {
....
}
};
....
}

}