Skip to content

Instantly share code, notes, and snippets.

@mpellegrini
Created February 23, 2012 14:40
Show Gist options
  • Save mpellegrini/1893124 to your computer and use it in GitHub Desktop.
Save mpellegrini/1893124 to your computer and use it in GitHub Desktop.
Example JMS Client to Produce and Consume Messages
// Step 1. Create an initial context to perform the JNDI lookup.
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, org.jboss.naming.remote.client.InitialContextFactory.class.getName());
env.put(Context.PROVIDER_URL, "remote://localhost:4447");
env.put(Context.SECURITY_PRINCIPAL, "username");
env.put(Context.SECURITY_CREDENTIALS, "password");
Context context = new InitialContext(env);
// Step 2. Lookup the connection factory
ConnectionFactory cf = (ConnectionFactory) context.lookup("jms/RemoteConnectionFactory");
// Step 3. Lookup the JMS queue
Queue queue = (Queue) context.lookup("jms/queue/test");
// Step 4. Create the JMS objects to connect to the server and manage a session
Connection connection = cf.createConnection("username", "password");
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// Step 5. Create a JMS Message Producer to send a message on the queue
MessageProducer producer = session.createProducer(queue);
// Step 6. Create a Text Message and send it using the producer
TextMessage message = session.createTextMessage("Hello World!");
producer.send(message);
System.out.println("Sent Message: " + message.getText());
// Step 7. Create a JMS Message Consumer to receive message from the queue
MessageConsumer messageConsumer = session.createConsumer(queue);
// Step 8. Start the Connection so that the server starts to deliver messages
connection.start();
// Step 9. Receive the message
TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000);
System.out.println("Received Message: " + messageReceived.getText());
// Finally, we clean up all the JMS resources
connection.close();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment