Search

30.2. Sending Messages from within Java EE components

download PDF
The JCA adapter can also be used for sending messages. The Connection Factory to use is configured by default in the <JBOSS_HOME>/jboss-as/server/<PROFILE>/deploy/hornetq/jms-ds.xml file and is mapped to java:/JmsXA.
Using this from within a Java EE component specifies that message sending is done as part of the JTA transaction being used by the component. If message sending fails, the overall transaction is rolled back and the message is re-sent. Here is an example of this from within an MDB:
@MessageDriven(name = "MDBMessageSendTxExample",
  activationConfig =
    {
      @ActivationConfigProperty
        (propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
      @ActivationConfigProperty
        (propertyName = "destination", propertyValue = "queue/testQueue")
    })
@TransactionManagement(value= TransactionManagementType.CONTAINER)
@TransactionAttribute(value= TransactionAttributeType.REQUIRED)
public class MDBMessageSendTxExample implements MessageListener
{
   @Resource(mappedName = "java:/JmsXA")
   ConnectionFactory connectionFactory;

   @Resource(mappedName = "queue/replyQueue")
   Queue replyQueue;

   public void onMessage(Message message)
   {
      Connection conn = null;
      try
      {
         //Step 9. We know the client is sending a text message so we cast
         TextMessage textMessage = (TextMessage)message;

         //Step 10. get the text from the message.
         String text = textMessage.getText();

         System.out.println("message " + text);

         conn = connectionFactory.createConnection();

         Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

         MessageProducer producer = sess.createProducer(replyQueue);

         producer.send(sess.createTextMessage("this is a reply"));

      }
      catch (Exception e)
      {
         e.printStackTrace();
      }
      finally
      {
         if(conn != null)
         {
            try
            {
               conn.close();
            }
            catch (JMSException e)
            { 
            }
         }
      }
   }
   }
You can also use the JMS JCA adapter for sending messages from EJBs (including Session, Entity and Message-Driven Beans), Servlets (including JSPs), and custom MBeans.
Red Hat logoGithubRedditYoutubeTwitter

Learn

Try, buy, & sell

Communities

About Red Hat Documentation

We help Red Hat users innovate and achieve their goals with our products and services with content they can trust.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. For more details, see the Red Hat Blog.

About Red Hat

We deliver hardened solutions that make it easier for enterprises to work across platforms and environments, from the core datacenter to the network edge.

© 2024 Red Hat, Inc.