12.07.2015 Views

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 13 ■ SENDING MESSAGESmethod asynchronously. Today, <strong>with</strong> EJB 3.1, asynchronous calls are possible between session beans<strong>with</strong>out the need of MDBs, allowing them to focus on integrating systems through messaging.Reference ImplementationOpen Message Queue (OpenMQ) is the reference implementation of JMS. It has been open source since2006 and can be used in stand-alone JMS applications or embedded in an application server. OpenMQ isthe default messaging provider for <strong>GlassFish</strong> and, as this book is being written, is reaching version 4.5. Italso adds many non-standard features such as the Universal Message Service (UMS), wildcard topicdestinations, XML message validation, clustering, and more.How to Send and Receive a MessageLet’s take a look at a simple example to get an idea of JMS. JMS employs producers, consumers, anddestinations. The producer sends a message to the destination, where the consumer is waiting for themessage to arrive. Destinations can be of two kinds: queues (for point-to-point communication) andtopics (for publish-subscribe communication). In Listing 13-1, a producer sends a text message to aqueue to which the consumer is listening.Listing 13-1. The Sender Class Produces a Message into a Queuepublic class Sender {public static void main(String[] args) {// Gets the JNDI contextContext jndiContext = new InitialContext();// Looks up the administered objectsConnectionFactory connectionFactory = (ConnectionFactory)jndiContext.lookup("jms/javaee6/ConnectionFactory");Queue queue = (Queue) jndiContext.lookup("jms/javaee6/Queue");// Creates the needed artifacts to connect to the queueConnection connection = connectionFactory.createConnection();Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);MessageProducer producer = session.createProducer(queue);// Sends a text message to the queueTextMessage message = session.createTextMessage();message.setText("This is a text message sent at " + new Date());producer.send(message);}}connection.close();380

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!