SlideShare una empresa de Scribd logo
1 de 45
Descargar para leer sin conexión
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

Más contenido relacionado

Más de Bruce Snyder

Más de Bruce Snyder (13)

Styles of Applicaton Integration Using Spring
Styles of Applicaton Integration Using SpringStyles of Applicaton Integration Using Spring
Styles of Applicaton Integration Using Spring
 
ActiveMQ In Action
ActiveMQ In ActionActiveMQ In Action
ActiveMQ In Action
 
Using Enterprise Integration Patterns as Your Camel Jockey
Using Enterprise Integration Patterns as Your Camel JockeyUsing Enterprise Integration Patterns as Your Camel Jockey
Using Enterprise Integration Patterns as Your Camel Jockey
 
Apache ActiveMQ and Apache ServiceMix
Apache ActiveMQ and Apache ServiceMixApache ActiveMQ and Apache ServiceMix
Apache ActiveMQ and Apache ServiceMix
 
Service-Oriented Integration With Apache ServiceMix
Service-Oriented Integration With Apache ServiceMixService-Oriented Integration With Apache ServiceMix
Service-Oriented Integration With Apache ServiceMix
 
Messaging With Apache ActiveMQ
Messaging With Apache ActiveMQMessaging With Apache ActiveMQ
Messaging With Apache ActiveMQ
 
Enterprise Messaging With ActiveMQ and Spring JMS
Enterprise Messaging With ActiveMQ and Spring JMSEnterprise Messaging With ActiveMQ and Spring JMS
Enterprise Messaging With ActiveMQ and Spring JMS
 
Taking Apache Camel For a Ride
Taking Apache Camel For a RideTaking Apache Camel For a Ride
Taking Apache Camel For a Ride
 
EIP In Practice
EIP In PracticeEIP In Practice
EIP In Practice
 
Service Oriented Integration With ServiceMix
Service Oriented Integration With ServiceMixService Oriented Integration With ServiceMix
Service Oriented Integration With ServiceMix
 
Taking Apache Camel For A Ride
Taking Apache Camel For A RideTaking Apache Camel For A Ride
Taking Apache Camel For A Ride
 
Messaging With ActiveMQ
Messaging With ActiveMQMessaging With ActiveMQ
Messaging With ActiveMQ
 
Taking Apache Camel For A Ride
Taking Apache Camel For A RideTaking Apache Camel For A Ride
Taking Apache Camel For A Ride
 

Último

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Último (20)

Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 

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