Consuming messages with an MDB

The last thing we must do to complete our business scenario is to retrieve the posted messages from the queue and create a new exhibition line in the database by using the persistence layer. To do so, follow these steps:

  1. Right-click on the Theater project's name, select New… in the top of the context menu, and then select Other….
  2. Type Message in the search field, select the Message-Driven Bean (EJB 3.x) entry, and click on Next.
  3. Configure the fields as shown in the following screenshot:
    Consuming messages with an MDB
  4. Click on Finish.

As a message carries an instance of class Exhibition, we will just extract and pass it to a persistence manager that will save the entity in following manner:

  1. Add a reference to inject the default persistence context:
    @PersistenceContext
    EntityManager em;
  2. In the onMessage method, we retrieve the object from the message and persist it. As the object is already an instance of exhibition, we didn't have to cast it, but let's do it for clarity and to print a message to the console:
    ObjectMessage om = (ObjectMessage) message;  
    
    try {
       Exhibition ex = (Exhibition) om.getObject();
    
       // Print the object received to the console
    StringBuilder msg = new StringBuilder();
              msg.append(ex.getMovie().getId())
             .append(", ")
             .append(ex.getRoom().getId())
             .append(", ")
             .append(ex.getDate())
             .append(", ")
             .append(ex.getHour());
             
             logger.info(msg.toString());
              
       em.persist(ex);
    
    } catch (JMSException e) {
        e.printStackTrace();
    }
  3. Save the file; now go to the Servers tab and release the changes to the server by clicking on Publish.

If everything went OK, you should see messages similar to the following in the Console tab, along with the normal output from the server:

5, 1, Tue Jan 01 00:00:00 BRST 2013, 1400
5, 1, Tue Jan 01 00:00:00 BRST 2013, 1400

You can also check for new records in the exhibition table of the database theater_db.

This covers the common usage of JMS queues, showing how to produce and consume messages. Let's check some parameters that we can set when using WebLogic Server to deal with JMS consumers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.108.175