This example shows you how to use a TemporaryQueue with ActiveMQ. First a temporary queue is created to send and receive a message and then deleted. Then another temporary queue is created and used after its connection is closed to illustrate its scope.
A TemporaryQueue is a JMS queue that exists only within the lifetime of its connection. It is often used in request-reply type messaging where the reply is sent through a temporary destination. The temporary queue is often created as a server resource, so after using, the user should call delete() method to release the resources. Please consult the JMS 1.1 specification for full details.
To run the example, simply type mvn verify -Pexample
from this directory
client-jndi.properties
file in the directory ../common/config
initialContext = getContext();
ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("/ConnectionFactory");
connection = cf.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue tempQueue = session.createTemporaryQueue();
MessageProducer messageProducer = session.createProducer(tempQueue);
TextMessage message = session.createTextMessage("This is a text message");
messageProducer.send(message);
MessageConsumer messageConsumer = session.createConsumer(tempQueue);
message = (TextMessage) messageConsumer.receive(5000);
messageConsumer.close();
messageProducer.close();
tempQueue.delete();
TemporaryQueue tempQueue2 = session.createTemporaryQueue();
connection.close();
connection = cf.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
try
{
messageConsumer = session.createConsumer(tempQueue2);
throw new Exception("Temporary queue cannot be accessed outside its lifecycle!");
}
catch (InvalidDestinationException e)
{
System.out.println("Exception got when trying to access a temp queue outside its scope: " + e);
}
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();
}
}