This example shows you how to use a transacted Session with ActiveMQ.
Firstly 2 messages are sent via the transacted sending session before being committed. This ensures that both message are sent
Secondly the receiving session receives the messages firstly demonstrating a message being redelivered after the session being rolled back and then acknowledging receipt of the messages via the commit method.
To run the example, simply type mvn verify
from this directory
client-jndi.properties
file in the directory ../common/config
initialContext = getContext();
Queue queue = (Queue) initialContext.lookup("/queue/exampleQueue");
ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("/ConnectionFactory");
connection = cf.createConnection();
connection.start();
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
MessageProducer messageProducer = session.createProducer(queue);
MessageConsumer messageConsumer = session.createConsumer(queue);
TextMessage message1 = session.createTextMessage("This is a text message1");
TextMessage message2 = session.createTextMessage("This is a text message2");
messageProducer.send(message1);
messageProducer.send(message2);
TextMessage receivedMessage = (TextMessage) messageConsumer.receive(5000);
session.commit();
receivedMessage = (TextMessage) messageConsumer.receive(5000);
session.rollback();
receivedMessage = (TextMessage) messageConsumer.receive(5000);
receivedMessage = (TextMessage) messageConsumer.receive(5000);
session.commit();
receivedMessage = (TextMessage) messageConsumer.receive(5000);
finally
block. Closing a JMS connection will automatically close all of its sessions, consumers, producer and browser objects
finally
{
if (initialContext != null)
{
initialContext.close();
}
if (connection != null)
{
connection.close();
}
}