This example shows you how to use a transactional Session with JBoss Messaging. It creates a transactional session. At first it sends out two messages and tries to receive without session commit. Then it commits the sending session and receives only one messages before it rolls back the receiving session. It then receives all the messages and commits the session.
Messages can be sent and received over transactional sessions. Messages in a transactional session will not be sent or acknowledged until the session is committed. It a session is rolled back, the produced messages will be destroyed and consumed messages will be recovered. Please consult the JMS 1.1 specification for full details.
To run the example, simply type ant
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();
}
}