This document provides code examples demonstrating how to send messages, and receive then both synchronously and asynchronously.
In general, JMS applications begin by looking up a ConnectionFactory instance from JNDI (the Java Naming and Directory Interface), and then using this to create Connection and then Session instances.
To create an InitialContext:
import java.util.Hashtable; import javax.naming.Context; import javax.naming.InitialContext; // ... Hashtable properties = new Hashtable(); properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.exolab.jms.jndi.InitialContextFactory"); properties.put(Context.PROVIDER_URL, "tcp://localhost:3035/"); Context context = new InitialContext(properties);
The above creates a initial context for the default server configuration.
To avoid hardcoding JNDI properties, they can be specified in an application resource file named jndi.properties located in the application's classpath. The properties must be listed as a set of key/value pairs, using the java.util.Properties file format. E.g:
java.naming.factory.initial=org.exolab.jms.jndi.InitialContextFactory java.naming.provider.url=tcp://myhost:3035
The code to construct the JNDI InitialContext becomes:
import javax.naming.Context; import javax.naming.InitialContext; // ... Context context = new InitialContext();
OpenJMS is pre-configured with a ConnectionFactory named "ConnectionFactory", which can be retrieved as follows:
import javax.jms.ConnectionFactory; // ... ConnectionFactory factory = (ConnectionFactory) context.lookup("ConnectionFactory");
A message is sent to a Destination, which may be a Queue (used for point-to-point messaging), or a Topic (used for publish-and-subscribe). A message is sent using a MessageProducer.
Messages are received from a Destination using a MessageConsumer.
Messages can be received synchronously or asynchronously.
import javax.jms.MessageConsumer; import javax.jms.TextMessage; // ... MessageConsumer receiver = session.createConsumer(destination); connection.start(); TextMessage message = (TextMessage) receiver.receive(); System.out.println("Received message: " + message.getText());
In the above, receiver blocks until it receives a message.
Messages are received asynchronously by registering a MessageListener:
import javax.jms.MessageConsumer; import javax.jms.MessageListener; import javax.jms.TextMessage; // ... MessageConsumer receiver = session.createConsumer(destination); receiver.setMessageListener(new MessageListener() { public void onMessage(Message message) { TextMessage text = (TextMessage) message; System.out.println("Received message: " + message.getText()); } }); // start the connection to enable message delivery connection.start();