JMS Basics
From Shrubbery
Work in Progress...
Contents |
What can I do with JMS?
- Implement the Java Enterprise version of the Observer Pattern
- Run tasks in the background using Message Driven Beans
- Accept incoming data asynchronously
- Run tasks serially (only one operation at a time). Serialized RPCs can be accomplished using temporary topics.
Connecting to a JMS Server
Here are the steps to connect to a JMS server:
- Look up the ConnectionFactory in JNDI
- Get a Connection from the ConnectionFactory.
- Get a Session from the Connection, specifiying the transaction support and acknowledgement mode.
- Look up the Destination in JNDI
- Create a Producer or a Consumer using the Session and specifying the Destination.
- Send/receive using the Producer or Consumer object.
When the program no longer needs to interact, release all the resources:
- Close the Producer or Consumer object.
- Close the Session object.
- Close the Connection object.
Example: Connecting to JBoss Messaging from a remote client
Preparation:
- Configure a destination on the server. See JBoss Messaging
- Set up the client's classpath.
Client code:
Sending a message on a queue
public static void main(String[] args)
{
QueueConnection connection = null;
QueueSession session = null;
MessageProducer producer = null;
try
{
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
env.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
env.put(Context.PROVIDER_URL, "jnp://localhost:1099");
InitialContext ctx = new InitialContext(env);
boolean transacted = false;
int acknowledgeMode = Session.AUTO_ACKNOWLEDGE;
ConnectionFactory connectionFactory = (ConnectionFactory)ctx.lookup("/ConnectionFactory");
connection = ((QueueConnectionFactory)connectionFactory).createQueueConnection();
session = connection.createQueueSession(transacted,acknowledgeMode);
Destination destination = (Destination) ctx.lookup("queue/someQueue");
producer = session.createProducer(destination);
Message message = session.createTextMessage("Hello there!");
producer.send(message);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (producer != null) {
try {
producer.close();
} catch (Exception ignore) {
}
}
if (session != null) {
try {
session.close();
} catch (Exception ignore) {
}
}
if (connection != null) {
try {
connection.close();
} catch (Exception ignore) {
}
}
}
}

