SlideShare a Scribd company logo
Enterprise Messaging With
    Spring JMS
    Bruce Snyder, Senior Software Engineer, SpringSource




Friday, July 8, 2011
Agenda

    • Very brief introduction to JMS
    • Synchronous JMS With Spring
    • Asynchronous JMS With Spring




                                       2

Friday, July 8, 2011
What is JMS?

    • JMS is:
           – An API for client-side communications with a JMS provider
           – Included in Java EE
                 • Also stand alone


    • JMS is not:
           – A spec for a message broker implementation




                                                                         3

Friday, July 8, 2011
JMS is an Abstraction




                            4

Friday, July 8, 2011
JMS Message




                       5

Friday, July 8, 2011
Point-to-Point Messaging




                               6

Friday, July 8, 2011
Publish/Subscribe Messaging




                                  7

Friday, July 8, 2011
Typical JMS Use




                       8

Friday, July 8, 2011
Raw JMS




                       9

Friday, July 8, 2011
JMS With Spring




                       10

Friday, July 8, 2011
Managed vs. Non-Managed JMS

    • Managed
           –   JMS provider in a Java EE container
           –   JMS resource pooling
           –   Transaction support
           –   Support for EJBs

    • Non-Managed
           – Stand alone JMS provider
           – Manual setup of JMS resources
           – No guarantee of transactions

    • Spring supports both environments

                                                     11

Friday, July 8, 2011
JMS With Spring




                       12

Friday, July 8, 2011
Spring JMS


                       • JMS Template
                          – Send and receive messages
                            synchronously

                       • Message Listener Container
                          – Receive messages asynchronously
                          – Message-Driven POJOs (MDPs)




                                                              13

Friday, July 8, 2011
JmsTemplate
                                                                       Synchronous
    •    browse()
           – Browse messages in a queue
    •    convertAndSend()
           – Send messages synchronously
           – Convert a Java object to a JMS message
    •    send()
           – Send a message synchronously using a MessageCreator
    •    receive() and receiveAndConvert()
           – Receive messages synchronously
    •    execute()
           – Provides access to callbacks for more complex scenarios
    •    receiveSelected() and receiveSelectedAndConvert()
           – Receive filtered messages synchronously




                                                                               14

Friday, July 8, 2011
The Spring JmsTemplate
                                                                      Synchronous

   <bean id="connectionFactory"
    class="org.apache.activemq.ActiveMQConnectionFactory"
    p:brokerURL="tcp://localhost:61616" />

     <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
      <constructor-arg value="FOO.TEST" />
     </bean>

     <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"
      p:connectionFactory-ref="connectionFactory"
      p:defaultDestination-ref="destination" />

     <bean id="messageProducer"
      class="org.bsnyder.spring.jms.producer.SimpleMessageProducer"
      p:jmsTemplate-ref="jmsTemplate" />




                                                                                 15

Friday, July 8, 2011
The Spring JmsTemplate
                                                                           Synchronous


         // Use the default destination
         jmsTemplate.convertAndSend("Hello World!");

         // Use a different destination
         jmsTemplate.convertAndSend(“TEST.BAR”, “Hello World!”);



         // Use a different destination
         String textMessage1 = (String) jmsTemplate.receiveAndConvert();

         // Use a different destination
         String textMessage2 = (String) jmsTemplate.receiveAndConvert(“TEST.BAR”);




                                                                                     16

Friday, July 8, 2011
The Spring JmsTemplate
                                                                            Synchronous
    • Using send() with a MessageCreator


              // Use a MessageCreator callback
              jmsTemplate.send(destination, new MessageCreator() {
                public Message createMessage(Session session)
                  throws JMSException {
                    TextMessage message = session.createTextMessage("Hello World!");
                    message.setIntProperty("someBusinessId", 22);
                    return message;
                 }
                });


              // Receive raw JMS message
              TextMessage message = jmsTemplate.receive();




                                                                                       17

Friday, July 8, 2011
The Spring JmsTemplate
                                                                Synchronous
    • Using execute() and the SessionCallback



       // Use a SessionCallback
       jmsTemplate.execute(new SessionCallback() {
        public Object doInJms(Session session) throws JMSException {
           Queue queue = session.createQueue("MY.TEST.QUEUE");
           MessageProducer producer = session.createProducer(queue);
           TextMessage message = session.createTextMessage("Hello World!");
           producer.send(message);
        }
       });




                                                                          18

Friday, July 8, 2011
The Spring JmsTemplate
                                                                  Synchronous
    • Using execute() with the ProducerCallback



      // Use a ProducerCallback
      jmsTemplate.execute(new ProducerCallback() {
          public Object doInJms(Session session, MessageProducer producer)
            throws JMSException {
              TextMessage message = session.createTextMessage("Hello World!");
              producer.send(destination, message);
          }
          return null;
        }
      });




                                                                            19

Friday, July 8, 2011
The Spring JmsTemplate
                                                                              Synchronous
    • Using JMS selector expression



              // Using a selector expression
              String selectorExpression =
                 “Timestamp BETWEEN 1218048453251 AND 1218048484330”;

              jmsTemplate.receiveSelected(destination, selectorExpression);




                                                                                      20

Friday, July 8, 2011
The Spring JmsTemplate
                                                                       Synchronous
    • Resolving JMS destinations
           – DynamicDestinationResolver (default)
                 • Look up destinations via a simple text name
                 • Just calls session.createQueue() and session.createTopic()
           – JndiDestinationResolver
                 • Option to fall back to DynamicDestinationResolver
           – BeanFactoryDestinationResolver
                 • Look up beans that are javax.jms.Destination objects




                                                                                21

Friday, July 8, 2011
The Spring JmsTemplate
                                                                         Synchronous
    • MessageConverter
           – SimpleMessageConverter
                 •     String <-> javax.jms.TextMessage
                 •     Map <-> javax.jms.MapMessage
                 •     Serializable object <-> javax.jms.ObjectMessage
                 •     byte[] <-> javax.jms.BytesMessage




                                                                                 22

Friday, July 8, 2011
The Spring JmsTemplate
                                                    Synchronous
    • JmsException hierarchy
           – Spring-specific unchecked exceptions
           – Corresponds to JMSException


    • Advantage
           – Automatic clean up of JMS resources




                                                            23

Friday, July 8, 2011
The Spring JmsTemplate
                                                             Synchronous
    • Automatically participates in transactions
    • Provides support for:
           – Java EE transactions
           – Spring local transactions (Spring JmsTransactionManager)
           – Spring global transactions (Spring JtaTransactionManager)

    • XA requires an XA capable ConnectionFactory
    • XA resource enlistment is provider specific




                                                                     24

Friday, July 8, 2011
The Spring JmsTemplate
                                                                      Synchronous
    • JmsTemplate does not provide resource pooling
           – Utilizes fresh connection/session for every invocation


    • JMS resource pooling is responsibility of JMS provider

    • Spring provides support
           – SingleConnectionFactory
                 • Returns same connection for all calls to createConnection()
                 • Ignores all calls to close()
           – CachingConnectionFactory
                 • Extends SingleConnectionFactory to add Session caching and
                   automatic Connection recovery


                                                                                 25

Friday, July 8, 2011
Spring JMS


                       • JMS Template
                         – Send and receive messages
                           synchronously

                       • Message Listener Container
                         – Receive messages asynchronously
                         – Message-Driven POJOs (MDPs)




                                                             26

Friday, July 8, 2011
Managed vs. Non-Managed JMS
                                                          Asynchronous

         • Non-Managed
                – JMS MessageConsumer registers a MessageListener
                – Manual lifecycle management


         • Managed
                – EJB Message-Driven Beans




                                                                    27

Friday, July 8, 2011
JMS Transaction Support
                                                           Asynchronous

         • Non-Managed XA Transactions
                – A JMS MessageConsumer can use various acknowledge
                  modes
                       •   AUTO_ACKNOWLEDGE
                       •   CLIENT_ACKNOWLEDGE
                       •   DUPS_OK_ACKNOWLEDGE
                       •   local JMS transaction
                – Standard JMS does not support asynchronous message
                  consumption as part of a XA transaction

         • Managed XA Transactions
                – Officially supported only by EJBs

                                                                    28

Friday, July 8, 2011
Spring Message-Driven POJOs
                                                             Asynchronous

         • DefaultMessageListenerContainer
                – Most commonly used container
                – Allows for dynamic scaling of queue consumers
                – Participates in external transactions


         • SimpleMessageListenerContainer
                – Very basic
                – Static configuration
                – No external transaction support




                                                                      29

Friday, July 8, 2011
DefaultMessageListenerContainer
                                                             Asynchronous
    • Highly configurable
           – Dynamic scale up/down of consumers
    • Threads managed by the container
           – Customizable via the Spring TaskExecutor
    • Resource caching
           – Connection, Session, MessageConsumer
           – Default is to cache nothing so as work in Java EE
             environments
           – See the setCacheLevel() method for more info
    • Works in managed and non-managed environments
    • Supports XA message consumption


                                                                      30

Friday, July 8, 2011
SimpleMessageListenerContainer
                                        Asynchronous
    • No dynamic scaling of consumers
    • No support for XA transactions




                                                 31

Friday, July 8, 2011
Supported Types of Message Listeners
                                                                Asynchronous
    • javax.jms.MessageListener interface
           – Standard Java EE interface
           – Threading is up to you
    • SessionAwareMessageListener interface
           – Spring-specific interface
           – Provides access to the Session object
                 • Very useful for request-response messaging
    • MessageListenerAdapter interface
           – Spring-specific interface
           – Allows for type-specific message handling
           – No JMS dependencies whatsoever


                                                                         32

Friday, July 8, 2011
MessageListener
                                                                       Asynchronous
    • Standard JMS MessageListener
    • Uses an onMessage() method


       public class MyMessageListener implements MessageListener {
         private static Logger LOG = Logger.getLogger(MyMessageListener.class);

           public void onMessage(Message message) throws JMSException {
             try {
                LOG.info("Consumed message: “ + message);
                // Do some processing here
             } catch (JMSException e) {
                LOG.error(e.getMessage(), e);
             }
           }




                                                                                  33

Friday, July 8, 2011
DefaultMessageListenerContainer
                                                                          Asynchronous
    • XML configuration

         <bean id="connectionFactory"
         class="org.apache.activemq.ActiveMQConnectionFactory"
           p:brokerURL="tcp://localhost:61616" />

          <bean id="messageListener"
           class="org.bsnyder.spring.jms.listener.SimpleMessageListener" />

          <jms:listener-container concurrency="5-10">
           <jms:listener destination="FOO.TEST" ref="messageListener"/>
          </jms:listener-container>




                                                                                   34

Friday, July 8, 2011
DefaultMessageListenerContainer
                                                                         Asynchronous
    • Use more than one listener

         <bean id="connectionFactory"
         class="org.apache.activemq.ActiveMQConnectionFactory"
           p:brokerURL="tcp://localhost:61616" />

          <bean id="widgetListener"
           class="org.bsnyder.spring.jms.listener.WidgetMessageListener" />

          <bean id="gadgetListener"
           class="org.bsnyder.spring.jms.listener.GadgetMessageListener" />

          <jms:listener-container concurrency="5-10">
           <jms:listener destination="PRODUCTS.WIDGETS" ref="widgetListener"/>
          <jms:listener destination="PRODUCTS.GADGETS" ref="gadgetListener"/>
          </jms:listener-container>




                                                                                  35

Friday, July 8, 2011
SessionAwareMessageListener
                                                                            Asynchronous
    • Provides access to the session
    • Uses an onMessage() method
   public class MySessionAwareMessageListener implements SessionAwareMessageListener {
     private static Logger LOG = Logger.getLogger(MySessionAwareMessageListener.class);

       public void onMessage(Message message, Session session) throws JMSException {
         try {
            LOG.info("Consumed message: “ + ((TextMessage)message).getText());
            // Send a reply message
              TextMessage newMessage = session.createTextMessage(“This is a test”);
              MessageProducer producer = session.createProducer(message.getJMSReplyTo());
              LOG.info("Sending reply message ");
              producer.send(newMessage);
           } catch (JMSException e) {
              LOG.error(e.getMessage(), e);
           }
       }
   }


                                                                                       36

Friday, July 8, 2011
DefaultMessageListenerContainer
                                                                          Asynchronous
    • XML configuration

         <bean id="connectionFactory"
         class="org.apache.activemq.ActiveMQConnectionFactory"
           p:brokerURL="tcp://localhost:61616" />

          <bean id="messageListener"
           class="org.bsnyder.spring.jms.listener.MySessionAwareMessageListener" />

          <jms:listener-container concurrency="5-10">
           <jms:listener destination="FOO.TEST" ref="messageListener"/>
          </jms:listener-container>




                                                                                      37

Friday, July 8, 2011
MessageListenerAdapter
                                                    Asynchronous
    • Handles all message content types
    • No reply message is sent (void return)


         public interface MessageDelegate {
           void processMessage(String text);
           void processMessage(Map map);
           void processMessage(byte[] bytes);
           void processMessage(Serializable obj);
         }




                                                             38

Friday, July 8, 2011
MessageListenerAdapter
                                                                        Asynchronous




          <bean id="messageDelegate"
           class="org.springframework.jms.listener.adapter.MessageListenerAdapter"
           p:defaultListenerMethod="processMessage">
           <constructor-arg>
            <bean class="org.bsnyder.spring.jms.adapter.MessageDelegateImpl" />
           </constructor-arg>
           <property name="messageConverter">
            <null/>
           </property>
          </bean>

          <jms:listener-container concurrency="5-10">
           <jms:listener destination="FOO.TEST" ref="messageDelegate" />
          </jms:listener-container>


                                                                                     39

Friday, July 8, 2011
MessageListenerAdapter
                                                         Asynchronous
    • Handles all raw JMS message types
    • No reply message is sent (void return)


         public interface MessageDelegate {
           void processMessage(TextMessage message);
           void processMessage(MapMessage message);
           void processMessage(BytesMessage message);
           void processMessage(ObjectMessage message);
         }




                                                                  40

Friday, July 8, 2011
MessageListenerAdapter
                                                                        Asynchronous




          <bean id="messageDelegate2"
           class="org.springframework.jms.listener.adapter.MessageListenerAdapter"
           p:defaultListenerMethod="processMessage">
           <constructor-arg>
            <bean class="org.bsnyder.spring.jms.adapter.MessageDelegate2Impl" />
           </constructor-arg>
           <property name="messageConverter">
            <null/>
           </property>
          </bean>

          <jms:listener-container concurrency="5-10">
           <jms:listener destination="FOO.TEST2" ref="messageDelegate2" />
          </jms:listener-container>


                                                                                     41

Friday, July 8, 2011
Local Transactions
                                                                        Asynchronous




          <bean id="messageDelegate"
           class="org.springframework.jms.listener.adapter.MessageListenerAdapter"
           p:defaultListenerMethod="processMessage">
           <constructor-arg>
            <bean class="org.bsnyder.spring.jms.adapter.MessageDelegateImpl" />
           </constructor-arg>
           <property name="messageConverter">
            <null/>
           </property>
          </bean>

          <jms:listener-container concurrency="5-10" acknowledge=”transacted”>
           <jms:listener destination="FOO.TEST" ref="messageDelegate" />
          </jms:listener-container>



                                                                                     42

Friday, July 8, 2011
Global Transactions
                                                                                 Asynchronous
          <bean id="activemqXaConnectionFactory"
           class="org.apache.activemq.ActiveMQXAConnectionFactory"
           p:brokerURL="tcp://localhost:61616" />

          <bean id="atomikosConnectionFactory"
           class="com.atomikos.jms.AtomikosConnectionFactoryBean"
           init-method="init" destroy-method="close">
            <property name="uniqueResourceName" value="simpleTransaction"/>
            <property name="xaConnectionFactory" ref="activemqXaConnectionFactory"/>
          </bean>

          <bean id="atomikosTransactionManager"
           class="com.atomikos.icatch.jta.J2eeTransactionManager" />
          <bean id="atomikosUserTransaction"
           class="com.atomikos.icatch.jta.J2eeUserTransaction" />

           <bean id="transactionManager"
             class="org.springframework.transaction.jta.JtaTransactionManager"
             p:transactionManager-ref="atomikosTransactionManager"
             p:userTransaction-ref="atomikosUserTransaction">
           </bean>
         ...

                                                                                          43

Friday, July 8, 2011
Global Transactions
                                                                                 Asynchronous

         ...

          <bean id="messageDelegate"
           class="org.springframework.jms.listener.adapter.MessageListenerAdapter"
           p:defaultListenerMethod="processMessage">
           <constructor-arg>
            <bean class="org.bsnyder.spring.jms.adapter.MessageDelegateImpl" />
           </constructor-arg>
           <property name="messageConverter">
            <null/>
           </property>
          </bean>

          <jms:listener-container concurrency="5-10"
           connection-factory="atomikosConnectionFactory"
           transaction-manager="transactionManager" acknowledge="transacted">
           <jms:listener destination="FOO.TEST" ref="messageDelegate" />
          </jms:listener-container>




                                                                                          44

Friday, July 8, 2011
Thank You!




           Q&A




Friday, July 8, 2011

More Related Content

PDF
Beyond Horizontal Scalability: Concurrency and Messaging Using Spring
PDF
ActiveMQ In Action - ApacheCon 2011
PPTX
Do we need JMS in 21st century?
PDF
Java EE 7, what's in it for me?
PPTX
JavaOne 2011 Recap
PDF
Tools Coverage for the Java EE Platform @ Silicon Valley Code Camp 2010
PPTX
Mule JMS Transport
PDF
Apc Memcached Confoo 2011
Beyond Horizontal Scalability: Concurrency and Messaging Using Spring
ActiveMQ In Action - ApacheCon 2011
Do we need JMS in 21st century?
Java EE 7, what's in it for me?
JavaOne 2011 Recap
Tools Coverage for the Java EE Platform @ Silicon Valley Code Camp 2010
Mule JMS Transport
Apc Memcached Confoo 2011

Similar to Enterprise Messaging With Spring JMS (20)

KEY
Introduction to JMS and Message-Driven POJOs
PDF
Message Driven Beans (6)
PDF
ActiveMQ In Action
DOCX
Java message service
PPT
Weblogic - Introduction to configure JMS
PDF
Spring integration
PPTX
Spring JMS
PDF
GIDS 2012: Java Message Service 2.0
PPTX
Java Message Service
PPT
Java Messaging Service
PPT
test
PPT
test
PPT
test
PPT
test
PPT
test
PPT
test
PPT
test
Introduction to JMS and Message-Driven POJOs
Message Driven Beans (6)
ActiveMQ In Action
Java message service
Weblogic - Introduction to configure JMS
Spring integration
Spring JMS
GIDS 2012: Java Message Service 2.0
Java Message Service
Java Messaging Service
test
test
test
test
test
test
test
Ad

More from Bruce Snyder (12)

PDF
Styles of Applicaton Integration Using Spring
PDF
Using Enterprise Integration Patterns as Your Camel Jockey
PDF
Apache ActiveMQ and Apache ServiceMix
PDF
Service-Oriented Integration With Apache ServiceMix
PDF
Messaging With Apache ActiveMQ
PDF
Enterprise Messaging With ActiveMQ and Spring JMS
PDF
Taking Apache Camel For a Ride
PDF
EIP In Practice
PDF
Service Oriented Integration With ServiceMix
PDF
Taking Apache Camel For A Ride
PDF
Messaging With ActiveMQ
PDF
Taking Apache Camel For A Ride
Styles of Applicaton Integration Using Spring
Using Enterprise Integration Patterns as Your Camel Jockey
Apache ActiveMQ and Apache ServiceMix
Service-Oriented Integration With Apache ServiceMix
Messaging With Apache ActiveMQ
Enterprise Messaging With ActiveMQ and Spring JMS
Taking Apache Camel For a Ride
EIP In Practice
Service Oriented Integration With ServiceMix
Taking Apache Camel For A Ride
Messaging With ActiveMQ
Taking Apache Camel For A Ride
Ad

Recently uploaded (20)

PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Machine learning based COVID-19 study performance prediction
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Approach and Philosophy of On baking technology
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Machine learning based COVID-19 study performance prediction
Per capita expenditure prediction using model stacking based on satellite ima...
Advanced methodologies resolving dimensionality complications for autism neur...
Spectral efficient network and resource selection model in 5G networks
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Electronic commerce courselecture one. Pdf
Empathic Computing: Creating Shared Understanding
Digital-Transformation-Roadmap-for-Companies.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
“AI and Expert System Decision Support & Business Intelligence Systems”
20250228 LYD VKU AI Blended-Learning.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
The Rise and Fall of 3GPP – Time for a Sabbatical?
Approach and Philosophy of On baking technology
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Bridging biosciences and deep learning for revolutionary discoveries: a compr...

Enterprise Messaging With Spring JMS

  • 1. Enterprise Messaging With Spring JMS Bruce Snyder, Senior Software Engineer, SpringSource Friday, July 8, 2011
  • 2. Agenda • Very brief introduction to JMS • Synchronous JMS With Spring • Asynchronous JMS With Spring 2 Friday, July 8, 2011
  • 3. What is JMS? • JMS is: – An API for client-side communications with a JMS provider – Included in Java EE • Also stand alone • JMS is not: – A spec for a message broker implementation 3 Friday, July 8, 2011
  • 4. JMS is an Abstraction 4 Friday, July 8, 2011
  • 5. JMS Message 5 Friday, July 8, 2011
  • 6. Point-to-Point Messaging 6 Friday, July 8, 2011
  • 7. Publish/Subscribe Messaging 7 Friday, July 8, 2011
  • 8. Typical JMS Use 8 Friday, July 8, 2011
  • 9. Raw JMS 9 Friday, July 8, 2011
  • 10. JMS With Spring 10 Friday, July 8, 2011
  • 11. Managed vs. Non-Managed JMS • Managed – JMS provider in a Java EE container – JMS resource pooling – Transaction support – Support for EJBs • Non-Managed – Stand alone JMS provider – Manual setup of JMS resources – No guarantee of transactions • Spring supports both environments 11 Friday, July 8, 2011
  • 12. JMS With Spring 12 Friday, July 8, 2011
  • 13. Spring JMS • JMS Template – Send and receive messages synchronously • Message Listener Container – Receive messages asynchronously – Message-Driven POJOs (MDPs) 13 Friday, July 8, 2011
  • 14. JmsTemplate Synchronous • browse() – Browse messages in a queue • convertAndSend() – Send messages synchronously – Convert a Java object to a JMS message • send() – Send a message synchronously using a MessageCreator • receive() and receiveAndConvert() – Receive messages synchronously • execute() – Provides access to callbacks for more complex scenarios • receiveSelected() and receiveSelectedAndConvert() – Receive filtered messages synchronously 14 Friday, July 8, 2011
  • 15. The Spring JmsTemplate Synchronous <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory" p:brokerURL="tcp://localhost:61616" /> <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue"> <constructor-arg value="FOO.TEST" /> </bean> <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate" p:connectionFactory-ref="connectionFactory" p:defaultDestination-ref="destination" /> <bean id="messageProducer" class="org.bsnyder.spring.jms.producer.SimpleMessageProducer" p:jmsTemplate-ref="jmsTemplate" /> 15 Friday, July 8, 2011
  • 16. The Spring JmsTemplate Synchronous // Use the default destination jmsTemplate.convertAndSend("Hello World!"); // Use a different destination jmsTemplate.convertAndSend(“TEST.BAR”, “Hello World!”); // Use a different destination String textMessage1 = (String) jmsTemplate.receiveAndConvert(); // Use a different destination String textMessage2 = (String) jmsTemplate.receiveAndConvert(“TEST.BAR”); 16 Friday, July 8, 2011
  • 17. The Spring JmsTemplate Synchronous • Using send() with a MessageCreator // Use a MessageCreator callback jmsTemplate.send(destination, new MessageCreator() { public Message createMessage(Session session) throws JMSException { TextMessage message = session.createTextMessage("Hello World!"); message.setIntProperty("someBusinessId", 22); return message; } }); // Receive raw JMS message TextMessage message = jmsTemplate.receive(); 17 Friday, July 8, 2011
  • 18. The Spring JmsTemplate Synchronous • Using execute() and the SessionCallback // Use a SessionCallback jmsTemplate.execute(new SessionCallback() { public Object doInJms(Session session) throws JMSException { Queue queue = session.createQueue("MY.TEST.QUEUE"); MessageProducer producer = session.createProducer(queue); TextMessage message = session.createTextMessage("Hello World!"); producer.send(message); } }); 18 Friday, July 8, 2011
  • 19. The Spring JmsTemplate Synchronous • Using execute() with the ProducerCallback // Use a ProducerCallback jmsTemplate.execute(new ProducerCallback() { public Object doInJms(Session session, MessageProducer producer) throws JMSException { TextMessage message = session.createTextMessage("Hello World!"); producer.send(destination, message); } return null; } }); 19 Friday, July 8, 2011
  • 20. The Spring JmsTemplate Synchronous • Using JMS selector expression // Using a selector expression String selectorExpression = “Timestamp BETWEEN 1218048453251 AND 1218048484330”; jmsTemplate.receiveSelected(destination, selectorExpression); 20 Friday, July 8, 2011
  • 21. The Spring JmsTemplate Synchronous • Resolving JMS destinations – DynamicDestinationResolver (default) • Look up destinations via a simple text name • Just calls session.createQueue() and session.createTopic() – JndiDestinationResolver • Option to fall back to DynamicDestinationResolver – BeanFactoryDestinationResolver • Look up beans that are javax.jms.Destination objects 21 Friday, July 8, 2011
  • 22. The Spring JmsTemplate Synchronous • MessageConverter – SimpleMessageConverter • String <-> javax.jms.TextMessage • Map <-> javax.jms.MapMessage • Serializable object <-> javax.jms.ObjectMessage • byte[] <-> javax.jms.BytesMessage 22 Friday, July 8, 2011
  • 23. The Spring JmsTemplate Synchronous • JmsException hierarchy – Spring-specific unchecked exceptions – Corresponds to JMSException • Advantage – Automatic clean up of JMS resources 23 Friday, July 8, 2011
  • 24. The Spring JmsTemplate Synchronous • Automatically participates in transactions • Provides support for: – Java EE transactions – Spring local transactions (Spring JmsTransactionManager) – Spring global transactions (Spring JtaTransactionManager) • XA requires an XA capable ConnectionFactory • XA resource enlistment is provider specific 24 Friday, July 8, 2011
  • 25. The Spring JmsTemplate Synchronous • JmsTemplate does not provide resource pooling – Utilizes fresh connection/session for every invocation • JMS resource pooling is responsibility of JMS provider • Spring provides support – SingleConnectionFactory • Returns same connection for all calls to createConnection() • Ignores all calls to close() – CachingConnectionFactory • Extends SingleConnectionFactory to add Session caching and automatic Connection recovery 25 Friday, July 8, 2011
  • 26. Spring JMS • JMS Template – Send and receive messages synchronously • Message Listener Container – Receive messages asynchronously – Message-Driven POJOs (MDPs) 26 Friday, July 8, 2011
  • 27. Managed vs. Non-Managed JMS Asynchronous • Non-Managed – JMS MessageConsumer registers a MessageListener – Manual lifecycle management • Managed – EJB Message-Driven Beans 27 Friday, July 8, 2011
  • 28. JMS Transaction Support Asynchronous • Non-Managed XA Transactions – A JMS MessageConsumer can use various acknowledge modes • AUTO_ACKNOWLEDGE • CLIENT_ACKNOWLEDGE • DUPS_OK_ACKNOWLEDGE • local JMS transaction – Standard JMS does not support asynchronous message consumption as part of a XA transaction • Managed XA Transactions – Officially supported only by EJBs 28 Friday, July 8, 2011
  • 29. Spring Message-Driven POJOs Asynchronous • DefaultMessageListenerContainer – Most commonly used container – Allows for dynamic scaling of queue consumers – Participates in external transactions • SimpleMessageListenerContainer – Very basic – Static configuration – No external transaction support 29 Friday, July 8, 2011
  • 30. DefaultMessageListenerContainer Asynchronous • Highly configurable – Dynamic scale up/down of consumers • Threads managed by the container – Customizable via the Spring TaskExecutor • Resource caching – Connection, Session, MessageConsumer – Default is to cache nothing so as work in Java EE environments – See the setCacheLevel() method for more info • Works in managed and non-managed environments • Supports XA message consumption 30 Friday, July 8, 2011
  • 31. SimpleMessageListenerContainer Asynchronous • No dynamic scaling of consumers • No support for XA transactions 31 Friday, July 8, 2011
  • 32. Supported Types of Message Listeners Asynchronous • javax.jms.MessageListener interface – Standard Java EE interface – Threading is up to you • SessionAwareMessageListener interface – Spring-specific interface – Provides access to the Session object • Very useful for request-response messaging • MessageListenerAdapter interface – Spring-specific interface – Allows for type-specific message handling – No JMS dependencies whatsoever 32 Friday, July 8, 2011
  • 33. MessageListener Asynchronous • Standard JMS MessageListener • Uses an onMessage() method public class MyMessageListener implements MessageListener { private static Logger LOG = Logger.getLogger(MyMessageListener.class); public void onMessage(Message message) throws JMSException { try { LOG.info("Consumed message: “ + message); // Do some processing here } catch (JMSException e) { LOG.error(e.getMessage(), e); } } 33 Friday, July 8, 2011
  • 34. DefaultMessageListenerContainer Asynchronous • XML configuration <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory" p:brokerURL="tcp://localhost:61616" /> <bean id="messageListener" class="org.bsnyder.spring.jms.listener.SimpleMessageListener" /> <jms:listener-container concurrency="5-10"> <jms:listener destination="FOO.TEST" ref="messageListener"/> </jms:listener-container> 34 Friday, July 8, 2011
  • 35. DefaultMessageListenerContainer Asynchronous • Use more than one listener <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory" p:brokerURL="tcp://localhost:61616" /> <bean id="widgetListener" class="org.bsnyder.spring.jms.listener.WidgetMessageListener" /> <bean id="gadgetListener" class="org.bsnyder.spring.jms.listener.GadgetMessageListener" /> <jms:listener-container concurrency="5-10"> <jms:listener destination="PRODUCTS.WIDGETS" ref="widgetListener"/> <jms:listener destination="PRODUCTS.GADGETS" ref="gadgetListener"/> </jms:listener-container> 35 Friday, July 8, 2011
  • 36. SessionAwareMessageListener Asynchronous • Provides access to the session • Uses an onMessage() method public class MySessionAwareMessageListener implements SessionAwareMessageListener { private static Logger LOG = Logger.getLogger(MySessionAwareMessageListener.class); public void onMessage(Message message, Session session) throws JMSException { try { LOG.info("Consumed message: “ + ((TextMessage)message).getText()); // Send a reply message TextMessage newMessage = session.createTextMessage(“This is a test”); MessageProducer producer = session.createProducer(message.getJMSReplyTo()); LOG.info("Sending reply message "); producer.send(newMessage); } catch (JMSException e) { LOG.error(e.getMessage(), e); } } } 36 Friday, July 8, 2011
  • 37. DefaultMessageListenerContainer Asynchronous • XML configuration <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory" p:brokerURL="tcp://localhost:61616" /> <bean id="messageListener" class="org.bsnyder.spring.jms.listener.MySessionAwareMessageListener" /> <jms:listener-container concurrency="5-10"> <jms:listener destination="FOO.TEST" ref="messageListener"/> </jms:listener-container> 37 Friday, July 8, 2011
  • 38. MessageListenerAdapter Asynchronous • Handles all message content types • No reply message is sent (void return) public interface MessageDelegate { void processMessage(String text); void processMessage(Map map); void processMessage(byte[] bytes); void processMessage(Serializable obj); } 38 Friday, July 8, 2011
  • 39. MessageListenerAdapter Asynchronous <bean id="messageDelegate" class="org.springframework.jms.listener.adapter.MessageListenerAdapter" p:defaultListenerMethod="processMessage"> <constructor-arg> <bean class="org.bsnyder.spring.jms.adapter.MessageDelegateImpl" /> </constructor-arg> <property name="messageConverter"> <null/> </property> </bean> <jms:listener-container concurrency="5-10"> <jms:listener destination="FOO.TEST" ref="messageDelegate" /> </jms:listener-container> 39 Friday, July 8, 2011
  • 40. MessageListenerAdapter Asynchronous • Handles all raw JMS message types • No reply message is sent (void return) public interface MessageDelegate { void processMessage(TextMessage message); void processMessage(MapMessage message); void processMessage(BytesMessage message); void processMessage(ObjectMessage message); } 40 Friday, July 8, 2011
  • 41. MessageListenerAdapter Asynchronous <bean id="messageDelegate2" class="org.springframework.jms.listener.adapter.MessageListenerAdapter" p:defaultListenerMethod="processMessage"> <constructor-arg> <bean class="org.bsnyder.spring.jms.adapter.MessageDelegate2Impl" /> </constructor-arg> <property name="messageConverter"> <null/> </property> </bean> <jms:listener-container concurrency="5-10"> <jms:listener destination="FOO.TEST2" ref="messageDelegate2" /> </jms:listener-container> 41 Friday, July 8, 2011
  • 42. Local Transactions Asynchronous <bean id="messageDelegate" class="org.springframework.jms.listener.adapter.MessageListenerAdapter" p:defaultListenerMethod="processMessage"> <constructor-arg> <bean class="org.bsnyder.spring.jms.adapter.MessageDelegateImpl" /> </constructor-arg> <property name="messageConverter"> <null/> </property> </bean> <jms:listener-container concurrency="5-10" acknowledge=”transacted”> <jms:listener destination="FOO.TEST" ref="messageDelegate" /> </jms:listener-container> 42 Friday, July 8, 2011
  • 43. Global Transactions Asynchronous <bean id="activemqXaConnectionFactory" class="org.apache.activemq.ActiveMQXAConnectionFactory" p:brokerURL="tcp://localhost:61616" /> <bean id="atomikosConnectionFactory" class="com.atomikos.jms.AtomikosConnectionFactoryBean" init-method="init" destroy-method="close"> <property name="uniqueResourceName" value="simpleTransaction"/> <property name="xaConnectionFactory" ref="activemqXaConnectionFactory"/> </bean> <bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.J2eeTransactionManager" /> <bean id="atomikosUserTransaction" class="com.atomikos.icatch.jta.J2eeUserTransaction" /> <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager" p:transactionManager-ref="atomikosTransactionManager" p:userTransaction-ref="atomikosUserTransaction"> </bean> ... 43 Friday, July 8, 2011
  • 44. Global Transactions Asynchronous ... <bean id="messageDelegate" class="org.springframework.jms.listener.adapter.MessageListenerAdapter" p:defaultListenerMethod="processMessage"> <constructor-arg> <bean class="org.bsnyder.spring.jms.adapter.MessageDelegateImpl" /> </constructor-arg> <property name="messageConverter"> <null/> </property> </bean> <jms:listener-container concurrency="5-10" connection-factory="atomikosConnectionFactory" transaction-manager="transactionManager" acknowledge="transacted"> <jms:listener destination="FOO.TEST" ref="messageDelegate" /> </jms:listener-container> 44 Friday, July 8, 2011
  • 45. Thank You! Q&A Friday, July 8, 2011